-1

I have a file named paper.json which has the following content:

[{
    "Question-no":1,
    "Question":"Answer the following Questions:",
    "Parts":[{
        "Question-no":"a",
        "Question":"This is part a"
    },{
        "Question-no":"b",
        "Question":"This is part b"
    },{
        "Question-no":"c",
        "Question":"This is part c"
    }]
},{
    "Question-no":2,
    "Question":"This is question 2",
    "Parts":[]
},{
    "Question-no":3,
    "Question":"This is question 3",
    "Parts":[]
},{
    "Question-no":4,
    "Question":"This is question 4",
    "Parts":[]
}]

I am using this code to access first object in the array:

// Java program to read JSON from a file 

import java.io.FileReader; 
import java.util.Iterator; 
import java.util.Map; 

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.*; 

class JSON 
{ 
    public static void main(String[] args) throws Exception 
    { 
        // parsing file "JSONExample.json" 
        Object obj = new JSONParser().parse(new FileReader("paper.json")); 


        JSONArray jo = (JSONArray) obj; 
        System.out.println(jo.getJSONObject(0));



    } 
} 

But on compiling it is saying that getJSONObject is not found. I have searched for the questions related to this but couldn't get any help. Is there any typo in my code?

Any help is appreciated!

Vipul Tyagi
  • 547
  • 3
  • 11
  • 29

1 Answers1

2

JSONArray does not have getJSONObject method. You can use get(int index)

JSONArray jo = (JSONArray) obj; 
System.out.println(jo.get(0));
Vikas
  • 6,868
  • 4
  • 27
  • 41
  • I read the above used method [here](https://stackoverflow.com/a/18977220/12103271) – Vipul Tyagi Apr 21 '20 at 11:49
  • You are using `org.json.simple.JSONArray` which doesn’t have this method. `org.codehaus.jettison.json` has `getJSONObject` – Vikas Apr 21 '20 at 11:52