我有一些代码可以将restful响应转换为递归结构。但是,我想要解析为树的内容被包装到“treeprop”属性中。是否有更方便的方法来解析真实内容?
ObjectMapper mapper = new ObjectMapper();
JsonFactory jfac = new JsonFactory();
JsonParser jp = jfac.createParser(inputStream);
JsonNode rootNode = mapper.readTree(jp);
JsonNode path = rootNode.path("treeprop");
String realContent = mapper.writeValueAsString(path);
MyTree mt = mapper.readValue(realContent, MyTree.class);
inputStream.close();
请注意,解析本身不是问题所在。上面的代码确实将inputStream正确转换为树。但是,json经常大于1MB,所以临时将它存储在String中是不能运行时效率的。
{
"treeprop": {
"id": 0,
"children": [
{
"id": 2,
"children": [
{
"id": 3,
"children": []
},
{
"id": 4,
"children": []
}
]
},
{
"id": 1,
"children": []
}
]
}
}
课程看起来大致像这样
class MyTree {
public Integer id;
public List<MyTree> children;
}
所以真正的问题是:是否有更有效的替代方案可以实现相同的目标:
JsonNode path = rootNode.path("treeprop");
String realContent = mapper.writeValueAsString(path);
MyTree mt = mapper.readValue(realContent, MyTree.class);
答案 0 :(得分:1)
public class MyTreeWrapper {
private MyTree treeprop;
// getter, setter
}
...
ObjectMapper mapper = new ObjectMapper();
MyTreeWrapper wrapper = mapper.readValue(inputStream, MyTreeWrapper.class);
MyTree tree = wrapper.getTreeprop();
替代:
MyTree tree = mapper.reader(MyTree.class).readValue(rootNode.path("treeprop"));