If you use custom serialization, you can get an unexpected effect if property name not equal to field name. Why the field is serialized twice?
My code sample:
class Mode {
@JsonProperty("mode")
@JsonSerialize(using = ModeSerializer.class)
private boolean isPublic;
public Mode(boolean isPublic) {
this.isPublic = isPublic;
}
public boolean isPublic() {
return isPublic;
}
}
Here my custom field serializer:
class ModeSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
String out = "private";
if (value) {
out = "public";
}
gen.writeString(out);
}
}
And here the test:
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Mode mode = new Mode(true);
String toJson = mapper.writeValueAsString(mode);
System.out.println(toJson);
}
}
And as a result I receive:
{"public":true,"mode":"public"}
What am I doing wrong?