Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

Roughly the code will look like:


// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
    
while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();
        
    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
        
        // do something here with the value...
}
Answer from momo on Stack Overflow
Top answer
1 of 5
123

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

Roughly the code will look like:


// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
    
while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();
        
    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
        
        // do something here with the value...
}
2 of 5
14

Another possibility is to use Gson (Note, I use lombok here to generates getters/setters, toString, etc):

package so7304002;

import java.util.List;
import java.util.Map;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonDemo {
    @Data
    private static class MyMap {
        private int count;

        @SerializedName("more_description")
        private String moreDescription;

        private int seq;
    }

    @Data
    private static class Product {
        private String product;

        private int id;

        @SerializedName("question_mark")
        private Map<String, MyMap> questionMark;
    }

    @Data
    private static class MyObject {
        private String status;

        @SerializedName("search_result")
        private List<Product> searchResult;
    }

    private static final String INPUT = ""; // your JSON

    public static void main(final String[] arg) {
        final MyObject fromJson = new Gson().fromJson(INPUT, 
            new TypeToken<MyObject>(){}.getType());
        final List<Product> searchResult = fromJson.getSearchResult();
        for (final Product p : searchResult) {
            System.out.println("product: " + p.getProduct() 
                + "\n" + p.getQuestionMark()+ "\n");
        }
    }
}

Output:

product: abc
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2), 
 8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)}

product: XYZ
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5), 
 845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6), 
 12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4), 
 257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)}
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ parsing a json object with nested dynamic values (with known keys)
r/javahelp on Reddit: Parsing a JSON object with nested dynamic values (with known keys)
October 16, 2024 -

In a problem I am working on, I have an endpoint where I will need to receive a JSON object which have a key that might contain different objects depending on the call. The list of possible objects is known in advance, but I am struggling with how best to model it. Splitting the endpoint into multiple is not an option.

The example looks something like this:

outerObject {
  ...,
  key: object1 | object2 | object3
}

object1 {
  "a": "a"
  "b": "b"
}

object2 {
  "c": 2
  "d": "d"
}

object3 {
  "e": 3,
  "f": 4
}

If I was writing it in Rust I would use an `enum` with structs for each of the different objects. This is for Java 21, so using sealed types is not yet an option (I might be able to upgrade, but I am not sure if the different

Using either Jackson or Gson I was think of representing it in one of their Json structures and then determining which object fits when the call is made.

Is this the best option or are there any more generic solutions?

Top answer
1 of 4
2
like that? https://stackoverflow.com/a/32777371
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Discussions

java - Retrieving values from nested JSON Object - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to parse dynamic nested JSON in Java using JSONObject.keys() - Stack Overflow
I am trying to parse through a nested JSON object to retrieve the value of the key "routing_bic". For some reason, it works with sample2.xml (i.e. "From main: 103"), but doesn't... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Parse nested object Json file in JAVA
Find answers to Parse nested object Json file in JAVA from the expert community at Experts Exchange More on experts-exchange.com
๐ŸŒ experts-exchange.com
September 11, 2017
How to parse Dynamic nested JSON with same keys and store in JAVA Class - Stack Overflow
I'm trying to read a complex payload(Tree structure) to perform PATCHMAPPING(Partial Update). To start with, I'm reading a JSON from the payload and trying to parse and store it's value. JSON DATA:... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to parse dynamic and nested JSON in java? - Rest assured API automation framework - YouTube
April 3, 2020 - Rest Assured is very popular in API Test Automation. REST Assured API can be used to invoke REST web services and match response content to test them. This v...
Top answer
1 of 7
36

Maybe you're not using the latest version of a JSON for Java Library.

json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.

JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java

After switching the library, you can refer to my sample code down below:

public static void main(String[] args) {
    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";

    JSONObject jsonObject = new JSONObject(JSON);
    JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
    Object level = getSth.get("2");

    System.out.println(level);
}

And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.

Hope that it helps.

2 of 7
15

You will have to iterate step by step into nested JSON.

for e.g a JSON received from Google geocoding api

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Bhopal, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            },
            "location" : {
               "lat" : 23.2599333,
               "lng" : 77.412615
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            }
         },
         "place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615

//recieve JSON in json object

        JSONObject json = new JSONObject(output.toString());
        JSONArray result = json.getJSONArray("results");
        JSONObject result1 = result.getJSONObject(0);
        JSONObject geometry = result1.getJSONObject("geometry");
        JSONObject locat = geometry.getJSONObject("location");

        //"iterate onto level of location";

        double lat = locat.getDouble("lat");
        double lng = locat.getDouble("lng");
๐ŸŒ
Medium
medium.com โ€บ @supriyaran โ€บ how-to-parse-nested-json-in-java-269ca24e260c
How to parse nested JSON in Java? | by Supriya Ranjan | Medium
October 7, 2021 - We have fid, ftype, fname and fppu as outer keys and id, type as inner keys that we will be testing with our code. Letโ€™s start with outer keys, here we are passing fid as the key. package jsonExample;import java.util.Iterator;import org.json.JSONArray;import org.json.JSONObject;public class jsonParseExample {public static void parseObject(JSONObject json, String key) {System.out.println("Key : "+key+" has value : "+json.get(key));}public static void getKey(JSONObject json, String key) {boolean exists = json.has(key);Iterator<?> keys;String nextKeys;if (!exists) {keys = json.keys();while (key
Find elsewhere
๐ŸŒ
Toolify
toolify.ai โ€บ gpts โ€บ efficient-java-json-parsing-dynamic-and-nested-json-121819
Efficient Java JSON Parsing: Dynamic and Nested JSON
Learn how to parse complex and nested JSON structures in Java using Rest Assured API automation framework.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-can-we-parse-a-nested-json-object-in-java
How can we parse a nested JSON object in Java?
Now, let's see how to parse a nested JSON object using the Gson library. Gson is developed by Google to help Java developers to work with JSON data. Let's see how to use it. In order to use this library, we need to add the Gson library. We can either download it from its official website or ...
๐ŸŒ
Websparrow
websparrow.org โ€บ home โ€บ how to parse nested json object in java
How to parse nested JSON object in Java - Websparrow
July 14, 2020 - package org.websparrow; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonNestedParseExample { public static void main(String[] args) { JSONParser jsonParser = new JSONParser(); Object object; try { object = jsonParser.parse(new FileReader("nestedobjects.json")); JSONObject jsonObject = (JSONObject) object; String name = (String) jsonObject.get("name");
๐ŸŒ
Experts Exchange
experts-exchange.com โ€บ questions โ€บ 29055896 โ€บ Parse-nested-object-Json-file-in-JAVA.html
Solved: Parse nested object Json file in JAVA | Experts Exchange
September 11, 2017 - I want the JAVA code to loop through each object and find the nested objects within it and print it as well. import java.io.FileReader; import java.util.Iterator; import java.util.Set; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * @author Crunchify.com */ public class CrunchifyJSONReadFromFile { @SuppressWarnings({ "rawtypes" }) public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader( "/Users/username/Documents/Work_Items.json")); JSONObject jsonObject = (JSONObject) obj; Set keys = jsonO
๐ŸŒ
ChillyFacts
chillyfacts.com โ€บ parse-nested-json-using-java
How to Parse Nested JSON using JAVA - ChillyFacts
November 9, 2017 - package com.chillyfacts.com; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class Get_Location_From_IP { public static void main(String[] args) { try { String ip = "74.125.45.100"; String key = "9d64fcfdfacc213csfsfc7ddsf4ef911dfe97b55e4fdsf696be3532bf8302876c09ebad06b"; String url = "http://api.ipinfodb.com/v3/ip-city/?key=" + key + "&ip=" + ip + "&format=json"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.se
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62844546 โ€บ how-to-parse-dynamic-nested-json-with-same-keys-and-store-in-java-class
How to parse Dynamic nested JSON with same keys and store in JAVA Class - Stack Overflow
The below is provided to give an idea of how to parse the JSON provided and may not necessarily be a complete solution. ... package org.test; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class GroupContainer { @JsonProperty(value = "data") private List<Group> data; public List<Group> getData() {return data;} public void setData(List<Group> data) {this.data = data;} }//class closing
Top answer
1 of 2
4

You can use JSONObject from http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar

public static void main(String[] args) {
        String input="{\r\n" + 
                "    \"Sample_01\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A1\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    },\r\n" + 
                "    \"Sample_02\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A2\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    }\r\n" + 
                "}";

        JSONObject jsonObject = new JSONObject(input);  


        Set<String> keys =jsonObject.keySet();
        for(String key:keys) {
            System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
        }
    }

If you again wants to parse the value of Sample_01 or Sample_02 or Sample_XX Check the instance of jsonObject like if(jsonObject.get(key) instanceof JSONObject) and Reiterate the loop

2 of 2
2

Extending the answer added by @Deepak. Both approaches are feasible but I preferred Gson as I was already using it.

Using JSONObject

JSONObject jsonObject = new JSONObject(input);  


Set<String> keys =jsonObject.keySet();
for(String key:keys) {
    System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
}

Using Gson

public static void main(String[] args) {
        
    String json = "{\"Sample_01\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.0.1.10\"],\"pool\":\"web_poolddd\"},\"web_poolddd\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.13.10\",\"192.0.14.11\"]}]}}},\"Sample_20\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.2.2.2\"],\"pool\":\"web_pool_data\"},\"web_pool_data\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.10.10\",\"192.0.10.11\"]}]}}}}";
    
    Type listType = new TypeToken<Map<String, Object>>(){}.getType();
    Gson gson = new Gson();
    Map<String,Object> myList = gson.fromJson(json, listType);

    JsonParser parser = new JsonParser();

    for (Map.Entry<String,Object> m : myList.entrySet())
    {
        System.out.println("==============");
        if(m.getValue() instanceof String){
            // get String value
        }else{ // if value is an Object
            
            System.out.println("VIP Sec: Name: "+m.getKey());
            Map<String,Object> myList1 = gson.fromJson(m.getValue().toString(), listType);
            for (Map.Entry<String,Object> m1 : myList1.entrySet())
            {
                if(!( m1.getValue() instanceof String)){
                    Map<String,Object> myList2 = gson.fromJson(m1.getValue().toString(), listType);
                    for (Map.Entry<String,Object> m2 : myList2.entrySet())
                    {
                         if(!( m2.getValue() instanceof String)){
                            Map<String,Object> myList3 = gson.fromJson(m2.getValue().toString(), listType);
                            for (Map.Entry<String,Object> m3 : myList3.entrySet())
                            {
                                if(m3.getKey().equals("virtualAddresses")){
                                    System.out.println("VIP Sec: IP Address: "+m3.getValue());
                                }
                                else if(m3.getKey().equals("pool")){
                                    System.out.println("Pool Sec: Name: "+m3.getValue());
                                }else if(m3.getKey().equals("monitors")){
                                    JsonArray monitors = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < monitors.size()){
                                        String monitor = monitors.get(count).getAsString();
                                        System.out.println("Monitor: "+monitor);
                                        count++;
                                    }
                                }else if(m3.getKey().equals("members")){
                                    JsonArray members = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < members.size()){
                                        // Parsing as Object to key values by key directly
                                        JsonObject mem = members.get(count).getAsJsonObject();
                                        String port = mem.get("servicePort").getAsString();
                                        System.out.println("Port: "+port);
                                        JsonElement ipAddrs = mem.get("serverAddresses");
                                        if(ipAddrs.isJsonArray()){
                                            JsonArray ips = ipAddrs.getAsJsonArray();
                                            int c = 0;
                                            while(c < ips.size()){
                                                String ip = ips.get(c).getAsString();
                                                System.out.println("IP: "+ip);
                                                c++;
                                            }
                                        }
                                        count++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



OUTPUT:

==============
VIP Sec: Name: Sample_01
VIP Sec: IP Address: [10.0.1.10]
Pool Sec: Name: web_poolddd
Monitor: http
Port: 80.0
IP: 192.0.13.10
IP: 192.0.14.11
==============
VIP Sec: Name: Sample_20
VIP Sec: IP Address: [10.2.2.2]
Pool Sec: Name: web_pool_data
Monitor: http
Port: 80.0
IP: 192.0.10.10
IP: 192.0.10.11

Read more about 2nd approach here

๐ŸŒ
Attacomsian
attacomsian.com โ€บ blog โ€บ jackson-map-dynamic-json-object
How to map a dynamic JSON object with Jackson
October 14, 2022 - Another way of storing the dynamic JSON property like address is to use the Java Map collection. This will also remove the extra Jackson dependency. Just change the address field data type to Map<String, Object> in the User class: public class User { public String name; public String email; ...
๐ŸŒ
Makeseleniumeasy
makeseleniumeasy.com โ€บ 2020 โ€บ 09 โ€บ 17 โ€บ rest-assured-tutorial-47-fetch-value-from-nested-json-array-using-jsonnode-jackson-at-method
REST Assured Tutorial 47 โ€“ Fetch Value From Nested JSON Array Using JsonNode โ€“ Jackson โ€“ At() Method
September 17, 2020 - We can get the value of a node using get() and path() methods of JsonNode class. We need to extract value with appropriate data types after using get() and path() methods. We just need to use an index to fetch an element of an array which is the core concept of an array.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ jackson โ€บ mapping nested values with jackson
Mapping Nested Values with Jackson | Baeldung
January 8, 2024 - Learn three ways to deserialize nested JSON values in Java using the Jackson library.