Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson deserialize JsonIdentityReference (alwaysAsId = true)

Tags:

java

json

jackson

Following up on this question: Question here

@JsonIdentityReference(alwaysAsId = true) and @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class) works great from the Serialization end, but not so well when it comes time to deserialize since it can't resolve the Object ID reference.

Is there a way to get this to deserialize? Writing a custom deserializer seems like overkill.

like image 299
psugar Avatar asked Aug 19 '13 03:08

psugar


People also ask

Does Jackson serialize getters?

Jackson by default uses the getters for serializing and setters for deserializing.

What does JsonPOJOBuilder do?

The @JsonPOJOBuilder annotation is used to configure a builder class to customize deserialization of a JSON document to recover POJOs when the naming convention is different from the default. The names of the bean's properties are different from those of the fields in JSON string.

What is @JsonManagedReference and @JsonBackReference?

The @JsonManagedReference annotation is a forward reference that includes during the serialization process whereas @JsonBackReference annotation is a backreference that omits during the serialization process. In the below example, we can implement @JsonManagedReference and @JsonBackReference annotations.

What is @JsonIdentityInfo?

@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during serialization/de-serialization.


1 Answers

Instead of a custom deserializer, you can use a simple setter deserializer:

public class Container {
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    @JsonIdentityReference(alwaysAsId = true)
    private Foo foo;

    public Foo getFoo() {
        return foo;
    }
    public Container setFoo(Foo foo) {
        this.foo = foo;
        return this;
    }
    @JsonProperty("foo")
    public void setFoo(String id) {
        foo = new Foo().setId(id);
    }
}

Example string of {"foo":"id1"} is serialized properly with this method in Jackson 2.5.2

like image 118
mtyurt Avatar answered Sep 17 '22 16:09

mtyurt