19

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.

Community
  • 1
  • 1
psugar
  • 1,897
  • 2
  • 18
  • 27

1 Answers1

10

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

mtyurt
  • 3,369
  • 6
  • 38
  • 57
  • 1
    This does not work if Foo has more properties than just the id and, thus, existing instances have to be linked. – koppor Jun 27 '17 at 11:30
  • 1
    setId shoudln't return instance of Foo, you should make it a builder insted – Komdosh Jan 17 '19 at 14:45