【问题标题】:Serialize parent-child object序列化父子对象
【发布时间】:2012-10-05 13:31:42
【问题描述】:

我有一个使用 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 按预期工作并返回一个包含所有子级的父级,但第二个方法 getChild 返回一个子级,没有对其有任何引用父母。

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

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

【问题讨论】:

  • 想要引用父对象还是实际的父对象?
  • 我更喜欢实际的对象。问题是,如何代表孩子们......

标签: java json rest serialization spring-mvc


【解决方案1】:

我通过升级到 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多