How to get values from JSONArray using Java [Simple-JSON]

44 Views Asked by At

I'm trying to get the value of "image" from the below shown JSON using JAVA:

Media.json:

[
    {
      "input": {
        "contentData": {
          "image":"Resources/RawImages/Media/InputImage/Media.jpg",
          "imageMetaData": {
            "DMLR":"",
            "imageCaptions":["cool"]
          }
        },
        "requestMetaData": {
          "requestId": "12345678",
          "locale": "en_US"
        }

      },
      "output": {
        "isTrue": true,
        "mMD": {
          "mcT": 0
        },
        "result": {
          "CR": 0.9039373397827148,
          "category": [
            {
              "Name": "Car",
              "score": 0.9039373397827148
            }
          ]
        }
      }
    }
  ]

Function:

public static String getImageFilePath() throws IOException, ParseException {
        JSONParser readJSON = new JSONParser();
        JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );

        JSONObject imgFilePath = (JSONObject) image2Json.get(1);


        return imgFilePath.toString();

Error Message:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
    at java.base/java.util.Objects.checkIndex(Objects.java:361)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at com.example.mediaservice.TestUtils.CommonTestUtils.getImageFilePath(CommonTestUtils.java:92)
    at com.example.mediaservice.TestUtils.CommonTestUtils.imageEncoder(CommonTestUtils.java:63)
    at com.example.mediaservice.TestUtils.CommonTestUtils.main(CommonTestUtils.java:37)

Process finished with exit code 1
2

There are 2 best solutions below

0
bhspencer On BEST ANSWER

The problem is that you are trying to get the item at position 1 out of the array and your array only contains 1 item. Arrays are zero based so to get the first item you need to get the item at position 0. Instead of:

JSONObject imgFilePath = (JSONObject) image2Json.get(1);

use:

JSONObject imgFilePath = (JSONObject) image2Json.get(0);

The exception you are seeing tells you this here:

IndexOutOfBoundsException: Index 1 out of bounds for length 1

4
Swapnil Padaya On

The reason why you are getting indexOutOfBound is because of

JSONObject imgFilePath = (JSONObject) image2Json.get(1);

You are trying to access index 1 whereas the size of the image2Json is only 1 so use 0 as the indexing of the arrays starts with 0.

The issue is that you are trying to just fetch JSONArray with an incorrect index with the code you have written till now.

JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );

This line will just load all JSONArray but when you call

String imagePath = (String) image2Json.get(Integer.parseInt("image"));

This will cause error because it can't find image key from the jsonArray.

Every JsonArray is made of JsonObject and so you must first refer to that jsonObject by doing something like.

JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );
for(int index = 0; index < image2Json.length(); index++) {
  JSONObject object = image2Json.getJSONObject(i);  jsonObject.
}

the object now consists of the below JSON

{
      "input":{
         "contentData":{
            "image":"Resources/RawImages/Media/InputImage/Media.jpg",
            "imageMetaData":{
               "DMLR":"",
               "imageCaptions":[
                  "cool"
               ]
            }
         },
         "requestMetaData":{
            "requestId":"12345678",
            "locale":"en_US"
         }
      },
      "output":{
         "isTrue":true,
         "mMD":{
            "mcT":0
         },
         "result":{
            "CR":0.9039373397827148,
            "category":[
               {
                  "Name":"Car",
                  "score":0.9039373397827148
               }
            ]
         }
      }
   }

And now we need to Refer to input json so for that we do.

JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );
for(int index = 0; index < image2Json.length(); index++) {
  JSONObject object = image2Json.getJSONObject(i);
  JSONObject input = object.getJSONObject("input");
}

Now input has following json:

"contentData":{
            "image":"Resources/RawImages/Media/InputImage/Media.jpg",
            "imageMetaData":{
               "DMLR":"",
               "imageCaptions":[
                  "cool"
               ]
            }

But still we need to dig deep and then we need contentData jsonObject.

JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );
for(int index = 0; index < image2Json.length(); index++) {
  JSONObject object = image2Json.getJSONObject(i);
  JSONObject input = object.getJSONObject("input");
  JSONObject contentData = object.getJSONObject("contentData");
}

Now contentData has the following Json:

"image":"Resources/RawImages/Media/InputImage/Media.jpg",
            "imageMetaData":{
               "DMLR":"",
               "imageCaptions":[
                  "cool"
               ]

and now we can access the image key by doing.

JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/"
                + "Media/InputJson/Media.json") );
for(int index = 0; index < image2Json.length(); index++) {
  JSONObject object = image2Json.getJSONObject(i);
  JSONObject input = object.getJSONObject("input");
  JSONObject contentData = input.getJSONObject("contentData");
  String image = contentData.getString("image");
}

String image = contentData.getString("image"); this image will have the value of image from your json.

to learn more on this I would recommend you to learn about JSON parsing and read more on JSON object, JSON array and key value pairing in json.