How to serialize only the ID of a child with Jackson

后端 未结 3 1981
面向向阳花
面向向阳花 2020-11-27 13:16

Is there a built-in way to only serialize the id of a child when using Jackson (fasterxml.jackson 2.1.1)? We want to send an Order via REST which has a Pe

3条回答
  •  一整个雨季
    2020-11-27 13:56

    You can write a custom serializer like this:

    public class ChildAsIdOnlySerializer extends StdSerializer {
    
      // must have empty constructor
      public ChildAsIdOnlySerializer() {
        this(null);
      }
    
      public ChildAsIdOnlySerializer(Class t) {
        super(t);
      }
    
      @Override
      public void serialize(Child value, JsonGenerator gen, SerializerProvider provider)
          throws IOException {
        gen.writeString(value.id);
      }
    

    Then use it by annotating the field with @JsonSerialize:

    public class Parent {
       @JsonSerialize(using = ChildAsIdOnlySerializer.class)
       public Child child;
    }
    
    public class Child {
        public int id;
    }
    

提交回复
热议问题