我在迭代这个结构时遇到了麻烦。我知道有一些方法使用杰克逊,我希望有人可以提供快速和可管理的解决方案。
JSON结构始终保持一致,每个孩子都有一个“子”字段,无论其大小如何。
我想为每个节点输出 field1,field 2和field3 。节点的层次结构无关紧要。
{
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": [{
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": [{
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": []
},
{
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": []
}
]
}, {
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": [{
"field1": "example data",
"field2": "example data2",
"field3": "example data3",
"children": []
}]
}]
}
答案 0 :(得分:2)
流API提供了一个简单的解决方案:
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(json);
while (parser.nextToken() != null) {
String name = parser.getCurrentName();
if ("field1".equals(name)) {
parser.nextToken(); // Advance to the field value
String value = parser.getText(); // Get the field value as a string
System.out.println(value);
}
}
parser.close();
通常,流API需要更多的工作才能使用,但在这种情况下(因为层次结构并不重要),这似乎是合适的。