Home > front end >  How to get nested keys and values from Json including arrays
How to get nested keys and values from Json including arrays

Time:09-22

I want the ability to return Json's keys and values, especially nested ones. The nested keys will have their parent key as a prefix. Example: This Json:

{
"name": "Josh",
"id": 23435,
"Group": {
    "class": "ranger",
    "level": 60
}

}

Keys will be in this format:

name, id, Group.class, Group.level

I have a recursive function that does it, and also returns the values as pairs in a map, but the problem happens with arrays within the Json. How can I support handling arrays inside the json?

This is the method:

   public static void findKeysAndValues(Object object, String key,Map <String, String> finalKeys) {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        jsonObject.keySet().forEach(childKey -> {
            findKeysAndValues(jsonObject.get(childKey), key != null ? key   "_"   childKey : childKey, finalKeys); //Also add requestPayLoad_ as parent key
        });
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        finalKeys.put(key,((JSONArray) object).toString());   //Also add requestPayLoad_ as parent key

        IntStream.range(0, jsonArray.length())
                .mapToObj(jsonArray::get)
                .forEach(jsonObject -> findKeysAndValues(jsonObject, key, finalKeys));
    }
    else{
        finalKeys.put(key,object.toString());
    }
}

And that's how you call it in the first time:

            Map<String,String> KeysAndValues = new HashMap<>();
            findKeysAndValues(jsonObject,null,KeysAndValues);

If there is a cleaner way also to get the results more correctly, and in my desired format, I'd love to hear more. *The original recursive function, before my enhancement, comes from this question: Retrieving all the keys in a nested json in java

CodePudding user response:

Library Josson can do the job.

https://github.com/octomix/josson

Deserialization

Josson josson = Josson.fromJsonString(
    "{"  
    "\"name\": \"Josh\","  
    "\"id\": 23435,"  
    "\"Group\": {"  
    "    \"class\": \"ranger\","  
    "    \"level\": 60,"  
    "    \"array\" : [0,1,2],"  
    "    \"objects\": ["  
    "      { \"x\": 1, \"y\": 2 },"  
    "      { \"x\": 3, \"y\": 4 },"  
    "      { \"x\": 5, \"y\": 6 }"  
    "    ]"  
    "  }"  
    "}");

Format style 1

JsonNode node = josson.getNode("flatten('.','[%d]')");
System.out.println(node.toPrettyString());

Output

{
  "name" : "Josh",
  "id" : 23435,
  "Group.class" : "ranger",
  "Group.level" : 60,
  "Group.array[0]" : 0,
  "Group.array[1]" : 1,
  "Group.array[2]" : 2,
  "Group.objects[0].x" : 1,
  "Group.objects[0].y" : 2,
  "Group.objects[1].x" : 3,
  "Group.objects[1].y" : 4,
  "Group.objects[2].x" : 5,
  "Group.objects[2].y" : 6
}

Format style 2

JsonNode node = josson.getNode("flatten('_')");
System.out.println(node.toPrettyString());

Output

{
  "name" : "Josh",
  "id" : 23435,
  "Group_class" : "ranger",
  "Group_level" : 60,
  "Group_array_0" : 0,
  "Group_array_1" : 1,
  "Group_array_2" : 2,
  "Group_objects_0_x" : 1,
  "Group_objects_0_y" : 2,
  "Group_objects_1_x" : 3,
  "Group_objects_1_y" : 4,
  "Group_objects_2_x" : 5,
  "Group_objects_2_y" : 6
}
  • Related