简体   繁体   中英

Retrieve all the nested keys of json object in java

How can I fetch all the nested keys of JSON object?

Below is the JSON input and it should return all the keys and subkeys with dot-separated like below output.

Input:

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

      ]
    }
  ]
}

Output:

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

You can do:

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

Usage:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM