Jackson, serialize one attribute of a reference

前端 未结 2 1954
一整个雨季
一整个雨季 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 {
        @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 {
        @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 {
        ....
    }
    

提交回复
热议问题