With the imports org.json.JSONArray and org.json.JSONObject

JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");

arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);

arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);

I did not include first array's second element for clarity. Hope you got the point though.

EDIT:

The previous answer was assuming you were using org.json.JSONObject and org.json.JSONArray.

For net.sf.json.JSONObject and net.sf.json.JSONArray :

JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");

arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);

arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);

Basically it's the same, replacing the method 'put' for 'element' in JSONObject, and 'put' for 'add' in JSONArray.

Answer from goten on Stack Overflow
Top answer
1 of 2
69

With the imports org.json.JSONArray and org.json.JSONObject

JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");

arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);

arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);

I did not include first array's second element for clarity. Hope you got the point though.

EDIT:

The previous answer was assuming you were using org.json.JSONObject and org.json.JSONArray.

For net.sf.json.JSONObject and net.sf.json.JSONArray :

JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();

JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();

JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");

JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");

arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);

arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);

Basically it's the same, replacing the method 'put' for 'element' in JSONObject, and 'put' for 'add' in JSONArray.

2 of 2
0

Here is one crude example. You should be able to refine. (You may be interested in this Java "tutorial" http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

(This example uses the JSON reference implementation included in Java EE (and available here: https://java.net/projects/jsonp/downloads/directory/ri)

package com.demo;
import java.io.FileWriter;
import java.io.IOException;
import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class JSONExample {
public static void main(String[] args) {
    FileWriter writer = null;
    try {
        writer = new FileWriter("C:\\Users\\Joseph White\\Downloads\\jsontext.txt");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JsonGenerator gen = Json.createGenerator(writer);

    gen.writeStartObject().write("name", "sample")
        .writeStartArray("def")
          .writeStartObject().write("setId", 1)
             .writeStartArray("setDef")
                .writeStartObject().write("name", "ABC").write("type", "STRING")
                .writeEnd()
                .writeStartObject().write("name", "XYZ").write("type", "STRING")
                .writeEnd()
            .writeEnd()
          .writeEnd()
            .writeStartObject().write("setId", 2)
              .writeStartArray("setDef")
                .writeStartObject().write("name", "abc").write("type", "STRING")
                .writeEnd()
                .writeStartObject().write("name", "xyz").write("type", "STRING")
                .writeEnd()
              .writeEnd()
            .writeEnd()
          .writeEnd()
        .writeEnd();

    gen.close();

}

 }
🌐
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 Jackson library. Jackson is also a well-known library for working with JSON data in Java.
Discussions

Parsing a JSON object with nested dynamic values (with known keys)
like that? https://stackoverflow.com/a/32777371 More on reddit.com
🌐 r/javahelp
4
2
October 16, 2024
java - How to access nested elements of json object using getJSONArray method - Stack Overflow
I want to access the value of the "entry" array object. I am trying to access: ... I am getting JSONException. Can someone please help me get the JSON array from the above JSON response? ... Okay, I can't help but I have tagged your question with 'java' so that others who can help will be able ... More on stackoverflow.com
🌐 stackoverflow.com
java - How to create a nested JSONObject - Stack Overflow
Creating nested JSON object for the following structure in Java using JSONObject? More on stackoverflow.com
🌐 stackoverflow.com
java - Retrieving values from nested JSON Object - Stack Overflow
@m.aibin Please note that all the ... org.json then, drap'n'drop all the java files to that package. And you rock! 2014-01-03T09:26:50.807Z+00:00 ... @m.aibin Also, plz note that, it's not a nested JSON Array, but a nested JSON object.... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-I-convert-deeply-nested-JSON-object-to-Java-object
How to convert deeply nested JSON object to Java object - Quora
Answer (1 of 4): things you need to do make model classes for each nested JSON object. Make a Java class define objects of each model class here now while parsing set data into model classes eg. Suppose Json contain Json1 json1 contain Json2 and so on… Json{. . . Json2{.. . Json3{…} M...
🌐
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.
🌐
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");
🌐
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 - A JSON Object is an unordered set of key/value pairs. A JSON Array is an ordered collection of values. The values could be objects or arrays. Nested JSON is a JSON file with its values being other JSON objects.
Find elsewhere
🌐
Quora
quora.com › How-can-we-write-a-JSON-file-with-nested-objects-in-Java
How can we write a JSON file with nested objects in Java? - Quora
Answer (1 of 2): Few Step’s you need to follow :- 1. First have on parent class which hold sub class and their ref it must be some POJO class. 2. Now set the all field value to parent class . 3. Now use any api like jackson,json,gson etc to convert parent class into nested json .
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");
🌐
Example Code
example-code.com › java › json_nested_objects.asp
Java JSON: Nested Objects
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
Medium
medium.com › @omarnyte › manipulating-nested-json-values-in-java-using-the-org-json-library-45df31fc4e46
Manipulating Nested JSON Values in Java Using the org.json Library | by Omar De Los Santos | Medium
September 3, 2018 - First, we’ll need to convert the JSON String to a JSONObject. Simply passing in the String to the JSONObject constructor will accomplish that as long as the String is properly formatted (including escaping double quotes with /. First, we’ll need to parse our way into the nested value.
🌐
Neptuneworld
neptuneworld.in › blog › how-access-simple-and-nested-json-object-java
How to access Simple and Nested JSON Object in Java ? - Neptuneworld.in
However, this time we access the nested object using the get() method twice. We first retrieve the address object using the get() method, and then retrieve the values of the keys in the address object using the get() method again. Finally, we print out the values to the console. In conclusion, accessing JSON objects in Java can be a bit tricky, especially when dealing with nested objects.
🌐
Baeldung
baeldung.com › home › json › jackson › mapping nested values with jackson
Mapping Nested Values with Jackson | Baeldung
January 8, 2024 - To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property. We can instruct Jackson to unpack the nested property by using a combination of @JsonProperty and some custom logic that we add to our Product class:
🌐
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 - package com.crunchify.tutorials; 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 JSON_EXPERTS { @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")); printJSON((JSONObject) obj); } catch (Exception e) { e.printStackTrace(); } } public static void printJSON(JSONObject jsonObj) { for (Object keyObj : jsonObj.keySet()) { String key = (String)keyObj; Object valObj = jsonObj.get(key); if (valObj instanceof JSONObject) { // call printJSON on nested object printJSON(valObj); } else { // print key-value pair System.out.println("key : "+key); System.out.println("value : "+valObj.toString()); } } } }
🌐
CodingTechRoom
codingtechroom.com › question › create-nested-json-object-java-jsonobject
How to Create a Nested JSON Object in Java Using JSONObject - CodingTechRoom
Creating nested JSON objects in Java can be straightforward using the `JSONObject` class from the `org.json` package.
🌐
Medium
samedesilva.medium.com › how-to-create-a-nested-json-object-payload-with-an-array-using-java-map-and-pass-it-as-the-payload-2aa0611fa2b3
How to create a Nested JSON Object payload and pass it as the payload of Playwright Java API post request. | by Sameera De Silva | Medium
December 13, 2023 - package com.payloads; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class CreatedNestedJSONObjectPayloadUsingJavaMapWithArray { public static void main(String[] args) { // Create a Gson instance Gson gson = new Gson(); // Create the main JSON object JsonObject mainJsonObjectPayload = new JsonObject(); // Add properties to the main JSON object since id doesn't have child can add directly. mainJsonObjectPayload.addProperty("id", 0); // Create and add the nested "category" JSON object since category has two children as id,name JsonObject categoryObject = new JsonObject(); categoryObject.addProperty("id", 0); categoryObject.addProperty("name", "string"); //After that add category to main object as a simple key and value.
🌐
QA Automation Expert
qaautomation.expert › 2021 › 11 › 08 › how-to-create-nested-json-object-using-jackson-api
How to create Nested JSON Object using POJO – Jackson API
August 20, 2024 - Last Updated On HOME In the previous tutorial, I explained the creation of JSON Array using POJO. In this tutorial, I will explain the creation of a nested JSON Object (JSON with multiple nodes) us…
🌐
Stack Overflow
stackoverflow.com › questions › 62210062 › nested-json-object-retrieval-in-java-example
Nested JSON Object Retrieval in JAVA Example - Stack Overflow
import org.json.simple.JSONObject; Class Demo{ public static void main(String args[]){ JSONObject json = new JSONObject(); JSONObject secondJson = new JSONObject(); secondJson.put("Secret","123214234"); secondJson.put("Code","123214"); secondJson.put("Data","Success"); json.put("Demo",secondJson); if(json.containsKey("Demo")) { JSONObject msg = (JSONObject)json.get("Demo"); if(msg.containsKey("Secret")) { String msg =Objects.toString(msg.get("Secret")), System.out.println(msg.get("Secret")); } } } }