Thomas Nairn
Thomas Nairn

Reputation: 1226

Ignore the Jackson JsonIdentityInfo during serialization

I'm currently using the @JsonIdentityInfo during deserialization and during serialization at some point in my application (During communication with certain clients) but some of my other clients simply can't use the @JsonIdentityInfo, is there away of ignoring it during serialization on some methods in spring?

For example:

[{id:5, innerobject:{id:1, name:"inner"}},
{id:6, innerobject:{id:1}}]

The second object with id:6 does not have a full innerobject, instead it uses the @JsonIdentityInfo to ignore the rest (As we already have it)

Focussing on the JacksonIdentityInfo (Server side), rather than focussing on the clientside as pointed out in the potential duplicate, which it is not. This is Jackson, not Gson.

Upvotes: 3

Views: 1910

Answers (2)

Atul K
Atul K

Reputation: 1044

Thanks to StaxMan, his approach worked for me. Below is the code snippet:

  • Custom JacksonAnnotationIntrospector to id creation:

import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.introspect.ObjectIdInfo;

public class CustomJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
 
    @Override
    public ObjectIdInfo findObjectIdInfo(Annotated ann) {
        return null;
    }

    @Override
    public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) {
        return null;
    }
}

  • To set it in mapper -

mapper.setAnnotationIntrospector(new CustomJacksonAnnotationIntrospector());

Upvotes: 1

StaxMan
StaxMan

Reputation: 116522

I don't think there is an easy way, but with bit of hackery it should be possible. The thing you can do is to create a custom sub-class of JacksonAnnotationIntrospector, override methods that look for @JsonIdentityInfo, and prevent them from detecting annotations.

Methods that seem to need overriding are findObjectIdInfo() and possibly findObjectReferenceInfo(). Just return null from both.

You can then register this introspector with ObjectMapper, and all reads using that mapper would work similar to removing of the annotation. Note that you can not dynamically change introspector: it must be set/changed before usage. So if you want to enable them in some context, you need to use 2 separate mappers.

As to how to configure Spring to use this I don't know, but you may want to sub-class ObjectMapper (MyNoObjectIdMapper extends ObjectMapper) and make it configure itself on constructor.

Upvotes: 2

Related Questions