Jackson, serialize one attribute of a reference

前端 未结 2 1924
一整个雨季
一整个雨季 2021-01-18 09:27

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

相关标签:
2条回答
  • 2021-01-18 09:48

    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 {
        ....
    }
    
    0 讨论(0)
  • 2021-01-18 09:59

    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.

    0 讨论(0)
提交回复
热议问题