如何迭代json对象的所有子节点? [英] How to iterate all subnodes of a json object?

查看:90
本文介绍了如何迭代json对象的所有子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历json对象的所有节点,并写出一个简单的键-值映射,如下所示:

I want to iterate through all nodes of a json object, and write out a plain key-value map, as follows:

{
    "name": [
        {
            "first": "John",
            "last": "Doe",
        "items": [
            {
                "name": "firstitem",
                "stock": 12
            },
            {
                "name": "2nditem",
                "stock:" 23
            }               
        ]
        }],
    "company": "John Company"
}

应导致:

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

这是将json字符串作为json对象的方法:

This is how to get the json string as a json object:

ObjectMapper mapper = new ObjectMapper(); //using jackson
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?

推荐答案

这将为您工作:

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());
    }
}

对于 json ,您给出的输出将是:

For the json you gave the output will be :

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

这篇关于如何迭代json对象的所有子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆