Jackson - custom serializer that overrides only specific fields

后端 未结 5 1572
灰色年华
灰色年华 2020-12-09 10:01

I know how to use a custom serializer in Jackson (by extending JsonSerializer), but I want the default serializer to work for all fields, except for just 1 fiel

5条回答
  •  抹茶落季
    2020-12-09 10:50

    In case you don't want to pollute your model with annotations, you could use mixins.

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.setMixInAnnotation(Student.class, StudentMixin.class);
    mapper.registerModule(simpleModule);
    

    And you want to override id field for example:

    public abstract class StudentMixin {
        @JsonSerialize(using = StudentIdSerializer.class)
        public String id;
    }
    

    Do whatever you need with the field:

    public class StudentIdSerializer extends JsonSerializer {
        @Override
        public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(String.valueOf(integer * 2));
        }
    }
    

提交回复
热议问题