Jackson-databind: Deserialize JsonManagedReference on many to many relations

Created on 27 Nov 2018  路  5Comments  路  Source: FasterXML/jackson-databind

Jackson Version: 2.9.7

Objects with a ManyToMany relationship which is managed by @JsonManagedReference/@JsonBackReference cannot be deserialized. This is easiest to show with an example.

public class JsonReferenceTest {
    class Customer {
        @JsonManagedReference("users")
        public Collection<User> users = new ArrayList<>();

        public String name = "company";
    }

    class User {
        @JsonBackReference("users")
        public Collection<Customer> customers = new ArrayList<>();

        public String name = "user";
    }

    ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void testDeserialize() throws IOException {
        String customer = "{\"name\":\"asdf\"}";

        objectMapper.readValue(customer, Customer.class);
    }
}

Running the following test results in:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'users': back reference type (java.util.Collection) not compatible with managed type (com.widewail.JsonReferenceTest$Customer)
 at [Source: (String)"{"name":"asdf"}"; line: 1, column: 1]

Digging into BeanDeserializerBase it looks like when checking that the back reference type matches the reference type it is not checking the contained type of the collection on the back reference side.

Most helpful comment

Am also facing the same issue.

All 5 comments

I'm looking for a solution but see no one has posted one

Am also facing the same issue.

Besides creating a custom Deserializable, does anyone could overpass this problem?

Correct: @JsonManagedReference only works on one-to-many cases, and not many-to-many.

For general-purpose handling of (possibly) cyclic dependencies, @JsonIdentityInfo may be used.

Was this page helpful?
0 / 5 - 0 ratings