When serializing a Java object which has other object references, I need to serialize only one attribute of the nested object(usual case of foreign key, so serialize the \"i
You can implement custom deserializer for this class and use it in User
class. Example implementation:
class AddressInformationIdJsonSerializer extends JsonSerializer<AddressInformation> {
@Override
public void serialize(AddressInformation value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.getId());
}
}
And configuration in User
class:
@JsonProperty(value = "defaultaddress")
@JsonSerialize(using = AddressInformationIdJsonSerializer.class)
public AddressInformation getDefaultAddress() {
return defaultAddress;
}
### Generic solution for all classes which implement one interface ###
You can create interface which contains String getId()
method:
interface Identifiable {
String getId();
}
Serializer for this interface could look like that:
class IdentifiableJsonSerializer extends JsonSerializer<Identifiable> {
@Override
public void serialize(Identifiable value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.getId());
}
}
And now, you can use this serializer for all Identifiable
implementations. For example:
@JsonProperty(value = "defaultaddress")
@JsonSerialize(using = IdentifiableJsonSerializer.class)
public AddressInformation getDefaultAddress() {
return defaultAddress;
}
of course: AddressInformation
have to implement this interface:
class AddressInformation implements Identifiable {
....
}
Just Found a way using Jackson 2.1+ .
Annotate object references with(this will pick only the id
attribute of AddressInformation
):
@JsonProperty(value = "defaultaddressid")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public AddressInformation getDefaultAddress() {
return defaultAddress;
}
Serialization works very well.