Java 如何迭代json对象的所有子节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48642450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate all subnodes of a json object?
提问by membersound
I want to iterate through all nodes of a json object, and write out a plain key-value map, as follows:
我想遍历一个json对象的所有节点,写出一个普通的键值映射,如下:
{
"name": [
{
"first": "John",
"last": "Doe",
"items": [
{
"name": "firstitem",
"stock": 12
},
{
"name": "2nditem",
"stock:" 23
}
]
}],
"company": "John Company"
}
Should result in:
应该导致:
name-first-1=John
name-last-1=Doe
name-items-name-1-1=firstitem (meaning the list index is always appended at the end of the name)
name-items-name-1-2=2nditem
company=John Company
This is how to get the json string as a json object:
这是获取 json 字符串作为 json 对象的方法:
ObjectMapper mapper = new ObjectMapper(); //using Hymanson
JsonNode root = mapper.readTree(json);
//TODO how loop all nodes and subnodes, and always get their key + value?
But how can I now iterate through all nodes and extract their key and content?
但是我现在如何遍历所有节点并提取它们的密钥和内容?
采纳答案by Daniel Taub
This will work for you :
这对你有用:
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
Map<String, String> map = new HashMap<>();
addKeys("", root, map, new ArrayList<>());
map.entrySet()
.forEach(System.out::println);
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map, List<Integer> suffix) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, suffix);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
suffix.add(i + 1);
addKeys(currentPath, arrayNode.get(i), map, suffix);
if (i + 1 <arrayNode.size()){
suffix.remove(arrayNode.size() - 1);
}
}
} else if (jsonNode.isValueNode()) {
if (currentPath.contains("-")) {
for (int i = 0; i < suffix.size(); i++) {
currentPath += "-" + suffix.get(i);
}
suffix = new ArrayList<>();
}
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
For the json
you gave the output will be :
对于json
您给出的输出将是:
name-items-name-1-2=2nditem
name-items-name-1-1=firstitem
name-items-stock-1-1=12
name-first-1=John
name-items-stock-1-2=23
company=John Company
name-last-1=Doe
回答by Thomas Weller
elements()gives you an iterator for subnodes and fields()gives you the properties.
elements()为您提供了一个用于子节点的迭代器,而fields()为您提供了属性。
回答by Dhiraj Pandit
You can convert JSON object to HashMap so you will get key and value pairs
您可以将 JSON 对象转换为 HashMap,这样您将获得键值对
here i use GSON library
在这里我使用 GSON 库
code snippet
代码片段
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, type);
so you can iterate this map for your purpose.
所以你可以根据你的目的迭代这张地图。
回答by Boris Chistov
Here is working sample, input is String
这是工作示例,输入是字符串
public static void main(String[] args) throws IOException {
JsonNode node = om.readTree(input);
LOG.info(node.toString());
process("", node);
}
private static void process(String prefix, JsonNode currentNode) {
if (currentNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) currentNode;
Iterator<JsonNode> node = arrayNode.elements();
int index = 1;
while (node.hasNext()) {
process(!prefix.isEmpty() ? prefix + "-" + index : String.valueOf(index), node.next());
index += 1;
}
}
else if (currentNode.isObject()) {
currentNode.fields().forEachRemaining(entry -> process(!prefix.isEmpty() ? prefix + "-" + entry.getKey() : entry.getKey(), entry.getValue()));
}
else {
LOG.info(prefix + ": " + currentNode.toString());
}
}