カスタムシリアル化を使用すると、プロパティ名がフィールド名と等しくない場合に予期しない結果が発生する可能性があります。 なぜフィールドが2回シリアル化されるのですか?プロパティの名前がフィールド名と等しくない場合、Jacksonカスタムシリアライザはフィールドを2回シリアル化します
私のコードサンプル:
class Mode {
@JsonProperty("mode")
@JsonSerialize(using = ModeSerializer.class)
private boolean isPublic;
public Mode(boolean isPublic) {
this.isPublic = isPublic;
}
public boolean isPublic() {
return isPublic;
}
}
ここに私のカスタムフィールド・シリアライザ:
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);
}
}
そして、ここでのテスト:
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);
}
}
そして、私が受け取る結果:
{"public":true,"mode":"public"}
私は間違っていますか?