java - 序列化父子对象

标签 java json rest serialization spring-mvc

我有一个使用 spring-mvc 构建的 REST 服务:

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="text/plain"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
    <property name="messageConverters">  
        <util:list id="beanList">  
            <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>  
        </util:list>  
    </property>  
</bean>  

为了避免序列化中的循环引用,我对对象进行了如下注释:

class Parent implements Serializable {
    int parent_id;
    @JsonManagedReference
    private List<Child> children; 
}

class Child implements Serializable {
    int child_id;
    @JsonBackReference
    private Parent parent;
}

我的 REST 服务公开了两个分别获取父级和子级的“方法”:

@RequestMapping(value = "/parent/{id}", method = RequestMethod.GET)
@ResponseBody public Parent getParent(@PathVariable int id , Model model) {
    Parent parent = myManager.getParent(id);
    return parent;
}

@RequestMapping(value = "/child/{id}", method = RequestMethod.GET)
@ResponseBody public Child getChild(@PathVariable int id , Model model) {
    Child child = myManager.getChild(id);
    return parent;
}

第一个方法 getParent 按预期工作并返回包含所有子级的 Parent,但第二个方法 getChild 返回单个子级,该子级没有有任何对其的引用父级。

json for parent: {"parent_id": 1, "children": [{"child_id":1},{"child_id":2}]}    
json for child: {"child_id":1}

所以我的问题是,如何设置序列化,以便 getChild 返回对其父对象的某种引用?

最佳答案

我通过升级到 Jackson 2.0 和 Spring 3.1.2(增加了对 jackson 2.0 的支持)解决了这个问题。

我现在像这样注释类:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property = "@parentId")
class Parent implements Serializable {
    int parent_id;
    private List<Child> children; 
}

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property = "@childId")
class Child implements Serializable {
    int child_id;
    private Parent parent;
}

并更新了 servlet-context 以使用 MappingJackson2JsonViewMappingJackson2HttpMessageConverter

对父级或子级的首次引用包含有关该对象的所有信息,而任何后续引用将仅打印 id(@childId 或 @parentId)

关于java - 序列化父子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747367/

相关文章:

java - Java 中的多个 XML 消化

Android(未处理的异常 : org. json.JSONException)

java - 如何在Java中解析JSON

java - 如何使用 ValidateUpdateListItem 方法将编码元数据上传到共享点?

rest - 在一个 http rest 请求中发送两个二进制消息

json - 如何以 JSON 格式从 Sonatype Nexus REST API 获取结果

java - 如何让程序读取文件中一行的字符,达到一定字符数后跳转到下一行?

java - 是否可以使用 Java Swing 存储构建的图像以便稍后显示?

java - 如何反序列化实体,将其置于托管上下文中,但不保留任何更改?

json - 处理来自服务器,JSON的数据时出现Swift错误