Jackson process string if annotated

Viewed 60

If the field has an annotation, I need to replace all the & characters in the string with § when deserializing, and do the opposite when serializing

For example i created an annotation and marked a field with it

public class SomeData {
    @MinecraftColorText
    private String str;
}

I need read this json:

{"str":"&6Some nice text"}

and in java object str field need be: §6Some nice text

Im need process only annotated fields, not all String

I wanted to do it with ContextualSerializer, but as I understand it, it replaces the standard serialization

1 Answers

So you should change your custom annotation @MinecraftColorText and add serialize and deserialize convertors:

@JsonDeserialize(converter = MinecraftDeserializeConverter.class)
@JsonSerialize(converter = MinecraftSerializeConverter.class)
@Retention(RUNTIME)
@Target(FIELD)
@JacksonAnnotationsInside
public @interface MinecraftColorText {
}

Deserialize converter:

public class MinecraftDeserializeConverter extends StdConverter<String, String> {

    @Override
    public String convert(final String s) {
        return s.replaceAll("&", "§");
    }
}

Serialize converter:

public class MinecraftSerializeConverter extends StdConverter<String, String> {

    @Override
    public String convert(final String s) {
        return s.replaceAll("§", "&");
    }
}

and just use:

  @MinecraftColorText
  private String str;

p.s: Don't forget about @JacksonAnnotationsInside that notify jackson about your custom serialization action. See more here

Related