How to serialize only the ID of a child with Jackson

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.

Leave a Comment