gpt4 book ai didi

java - 序列化父子对象

转载 作者:行者123 更新时间:2023-12-01 15:07:48 26 4
gpt4 key购买 nike

我有一个使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com