Jackson2多次反序列化

时间:2013-08-01 07:33:11

标签: json jackson

我有两个类,事件和用户有很多关系。

public class Event {

    private int id;

  private List<Users> users;
}

public class User {
        private int id;

      private List<Event> events;
}

我已阅读@JsonIdentityInfo注释应该有帮助,但我看不到这个例子。

3 个答案:

答案 0 :(得分:5)

您可以通过以下方式使用@JsonIdentityInfoUser这两个类中的Event

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
}

...和

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
}

您可以根据需要使用任何ObjectIdGenerator。现在,对应于多对多映射的对象的序列化和反序列化将成功:

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);
}

希望这有帮助。

答案 1 :(得分:1)

我来到这里&#34;谷歌搜索&#34;,所以我最终使用@ Jackall的anwers,带一点mod

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

这是因为我的DTO有一个名为&#34; id&#34;的属性,就像问题中的事件和用户类一样。

答案 2 :(得分:0)

尝试在JsonIdentityInfo注释中使用“scope”属性:

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