How to serialize only the ID of a child with Jackson

后端 未结 3 2009
面向向阳花
面向向阳花 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 14:06

    There are couple of ways. First one is to use @JsonIgnoreProperties to remove properties from a child, like so:

    public class Parent {
       @JsonIgnoreProperties({"name", "description" }) // leave "id" and whatever child has
       public Child child; // or use for getter or setter
    }
    

    another possibility, if Child object is always serialized as id:

    public class Child {
        // use value of this property _instead_ of object
        @JsonValue
        public int id;
    }
    

    and one more approach is to use @JsonIdentityInfo

    public class Parent {
       @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
       @JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
       public Child child; // or use for getter or setter
    
       // if using 'PropertyGenerator', need to have id as property -- not the only choice
       public int id;
    }
    

    which would also work for serialization, and ignore properties other than id. Result would not be wrapped as Object however.

提交回复
热议问题