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...
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
Jackson doesn't (by default) care about fields. It will simply serialize everything provided by getters and deserialize everything with a matching setter.
Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With