带有子对象的pojos的JSON序列化 [英] JSON Serialization of pojos with child objects
问题描述
假设我有一个具有以下接口的宁静的Web服务:
Let's say I have a restful webservice with the following interfaces:
GET /some/parent
这将返回类似的内容
[
{
urn: "/some/parent/1",
name: "parent1",
children: [ "/some/child1", "/some/child2" ]
},
{
urn: "/some/parent/2",
name: "parent2",
children: [ "/some/child3", "/some/child4" ]
}
]
而且,我已经
GET /some/parent/{id}
返回如下内容:
{
urn: /some/parent/1,
name: parent1,
children: [
{
urn: "/some/child1",
name: "child1"
},
{
urn: "/some/child2",
name: "child2"
}
]
}
因此,当请求父母列表时,每个父母的json表示形式将与孩子骨灰盒一起列出.请求特定的父资源时,json表示形式将包含子json表示形式的列表.
So, when requesting a list of parents, the json representations for every parent will be list with the child urns. When requesting a specific parent resource the json representation will contain a list of child json representations.
使用jersey的常见方法是定义两个简单的Java pojos和一个简单的Resource:
With jersey the common way would be to define two simple java pojos and a simple Resource:
public class Parent {
private String id;
private String name;
private List<String> childIds;
...
@JsonIgnore
public String getId()...
@JsonProperty
public String getUrn()...
}
public class Child {
private String id:
private String name;
...
@JsonIgnore
public String getId()...
@JsonProperty
public String getUrn()...
}
@Path("/some/parent")
@Produces(MediaType.APPLICATION_JSON)
public class ParentResource() {
@GET
public List<Parent> findAll() {
List<Parent> result = // some database query call
return result;
}
@GET
@Path("{id}")
public Parent find(@PathParam("id") String id) {
Parent parent = // some database call
return parent;
}
}
在上述情况下如何注入儿童the/物体?有没有最佳做法?您如何解决这个问题?
How can I inject the child urns/objects in the above scenarios? Are there any best practices? How do you solve this?
谢谢.
推荐答案
在这种情况下,我宁愿制作一个扩展的Parent类,如下所示:
In this case I would rather make an extended Parent class like this:
public class ParentExtended extends Parent {
private List<Child> childrenObjects;
public ParentExtended(Parent parent) {
this.id = parent.getId();
...
}
@JsonProperty("children")
public List<Child> getChildrenObjects() { ... }
@Override
@JsonIgnore
public List<String> getChildren() { ... }
}
@Path("/some/parent")
@Produces(MediaType.APPLICATION_JSON)
public class ParentResource() {
@GET
public List<Parent> findAll() {
List<Parent> result = // some database query call
return result;
}
@GET
@Path("{id}")
public ParentExtended find(@PathParam("id") String id) {
Parent parent = // some database call
ParentExtended parentEx = new ParentExtended(parent);
for (String childId : parent.getChildren()) {
parentEx.getChildrenObjects().add(// fetch the child object);
}
return parentEx;
}
}
这不是一个很好的方法.我愿意接受其他选择...
It is not a very nice way. I am open to other alternatives...
这篇关于带有子对象的pojos的JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!