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
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