Home » Java » java – How to fetch the entire JSON array based on index using simple JSON Library-Exceptionshub

java – How to fetch the entire JSON array based on index using simple JSON Library-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I just have the below format of JSON request: (The original JSON is huge so sharing the sample from blog)

Sample Request:

{
  "testData": [
    {
      "firstName": "Lokesh",
      "lastName": "Gupta",
      "website": "howtodoinjava.com"
    },
    {
      "firstName": "Brian",
      "lastName": "Schultz",
      "website": "example.com"
    }
  ]
}

I just have below method which should get the each index of the above JSONArray. The above request should return size() == 2. And I just want to print the entire array[0], and array[1] in each iteration as like below.

public static void constructJSON(CheckoutDTO result)throws Exception
    {
        String jsonBody = result.getJson();
        JSONObject object = parseAndReturnObj(jsonBody);
        JSONArray array= (JSONArray) object.get("testData");
        int index=0;
        for(int i=0;i<array.size();i++)
        {
            index++;
            JSONObject objects = (JSONObject) array.get(""); 

            Sysout(objects); // Here I just want to print the array[0] index as entire JSONObject.
            }       

        }
    }

The above code I just want to print the each index of the array. Like the first iteration I just want to print below:

array[0]:

  {
        "firstName": "Lokesh",
        "lastName": "Gupta",
        "website": "howtodoinjava.com"
  }

Second Iteration It should print below:

array[1]:

     {
            "firstName": "Brian",
            "lastName": "Schultz",
            "website": "example.com"
     }

The above request may have “n” number of array[n]. I just want to print the Systout(Objects) in the for loop as above format.

Using Simple json library to read the JSONObject.

   <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
    </dependency>

Can anyone help me to achieve this?

How to&Answers:

You can simply write System.out.println(object);. JSONObject‘s toString() method will automatically convert it to json. Your for loop can be modified as

for (int i = 0; i < array.size(); i++) {
    index++;
    JSONObject object = (JSONObject) array.get(i);
    System.out.println(object);
}