在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]