rOrlig
rOrlig

Reputation: 2529

Jackson2 many to many deserialization

I have two classes Events and Users which have a many to many relationship.

public class Event {

    private int id;

  private List<Users> users;
}

public class User {
        private int id;

      private List<Event> events;
}

I have read @JsonIdentityInfo annotation is supposed to help but I cannot see an example of this.

Upvotes: 2

Views: 6879

Answers (3)

Jonathan Perrotta
Jonathan Perrotta

Reputation: 101

I came here "googling", so I ended up using @Jackall's anwers, with a little mod

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

This is 'cause my DTO's have a property called "id", like Event and User classes from the question.

Upvotes: 1

ThiagoDP
ThiagoDP

Reputation: 9

Try to use the "scope" property, inside your JsonIdentityInfo annotation:

@JsonIdentityInfo(
    generator = ObjectIdGenerators.UUIDGenerator.class,   
    property="@UUID",
    scope=YourPojo.class
)

Upvotes: 0

Vinod
Vinod

Reputation: 1130

You can use @JsonIdentityInfo in the two classes User and Event this way:

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property="@UUID")
public class User
{
    private int id;
    private List<Event> events;

    // Getters and setters
}

... and

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property="@UUID")
public class Event
{
    private int id;
    private List<User> users;

    // Getters and setters
}

You can use any of the ObjectIdGenerators as appropriate. Now, serialization and deserialization of the objects that correspond to the many to many mapping will succeed:

public static void main(String[] args) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    Event event1 = new Event();
    event1.setId(1);
    Event event2 = new Event();
    event2.setId(2);

    User user = new User();
    user.setId(10);

    event1.setUsers(Arrays.asList(user));
    event2.setUsers(Arrays.asList(user));
    user.setEvents(Arrays.asList(event1, event2));

    String json = objectMapper.writeValueAsString(user);
    System.out.println(json);

    User deserializedUser = objectMapper.readValue(json, User.class);
    System.out.println(deserializedUser);
}

Hope this helps.

Upvotes: 5

Related Questions