如何使用java对象和Jackson递归创建这个json内容? :
{
"children": [
{
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"size": 3938
},
{
"name": "TestCLuster",
"size": 3938
}
]
}
],
"name": "analytics"
}
],
"name": "flare"
}
到目前为止,这是我的对象结构,一个名为DendogramVO的父类和一个名为Children的子类,它也有一个子列表:
import java.util.List;
public class DendogramVO {
private List<Children> children;
private String name;
public List<Children> getChildren() {
return this.children;
}
public void setChildren(List<Children> children) {
this.children = children;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.List;
public class Children {
private List<Children> children;
private String name;
public List<Children> getChildren() {
return children;
}
public void setChildren(List<Children> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
答案 0 :(得分:2)
请注意,您的JSON包含未知属性。您需要将ObjectMapper
配置为在遇到它们时不要失败(或将它们添加到您的班级)
String s="{ \"children\": [ { \"children\": [ { \"name\": \"cluster\", \"children\": [ { \"name\": \"AgglomerativeCluster\", \"size\": 3938 }, { \"name\": \"TestCLuster\", \"size\": 3938 } ] } ], \"name\": \"analytics\" } ], \"name\": \"flare\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Children children = mapper.readValue(s, Children.class);
System.out.println(children.getChildren());
使用简单的Children#toString()
打印
[[children = [[children = [[children = null, name = AgglomerativeCluster], [children = null, name = TestCLuster]], name = cluster]], name = analytics]]