How to serialize only the ID of a child with Jackson

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 Person reference. The person object however is quite complex and we could refresh it on the server side, so all we need is the primary key.

Or do I need a custom serializer for this? Or do I need to @JsonIgnore all other properties? Would that prevent the Person data from being sent back when requesting an Order object? I'm not sure yet if I'll need that but I'd like to have control over it if possible...


Solution 1:

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.

Solution 2:

You can write a custom serializer like this:

public class ChildAsIdOnlySerializer extends StdSerializer<Child> {

  // must have empty constructor
  public ChildAsIdOnlySerializer() {
    this(null);
  }

  public ChildAsIdOnlySerializer(Class<Child> 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;
}