微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在java中检索json对象的所有嵌套键

如何解决在java中检索json对象的所有嵌套键

如何获取 JSON 对象的所有嵌套键?

下面是 JSON 输入,它应该返回所有用点分隔的键和子键,如下输出

输入:

{
  "name": "John","localizedname": [
    {
      "value": "en-US",}
  ],"entityRelationship": [
    {
      "entity": "productOffering","description": [
        {
          "locale": "en-US","value": "New Policy Description"
        },{
          "locale": "en-US","value": "New Policy Description"
        }

      ]
    }
  ]
}

输出

["name","localizedname","localizedname.value","entityRelationship","entityRelationship.entity","entityRelationship.description","entityRelationship.description.locale","entityRelationship.description.value"] 

解决方法

你可以这样做:

public void findAllKeys(Object object,String key,Set<String> finalKeys) {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        jsonObject.keySet().forEach(childKey -> {
            findAllKeys(jsonObject.get(childKey),key != null ? key + "." + childKey : childKey,finalKeys);
        });
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        finalKeys.add(key);

        IntStream.range(0,jsonArray.length())
                .mapToObj(jsonArray::get)
                .forEach(jsonObject -> findAllKeys(jsonObject,key,finalKeys));
    }
    else{
        finalKeys.add(key);
    }
}

用法:

Set<String> finalKeys = new HashSet<>();
findAllKeys(json,null,finalKeys);
System.out.println(finalKeys);

输出:

[entityRelationship.entity,localizedName,localizedName.value,entityRelationship,name,entityRelationship.description.value,entityRelationship.description,entityRelationship.description.locale]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。