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

0

1 Answer 1

2

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

JSONArray jo = (JSONArray) obj; 
System.out.println(jo.get(0));
Sign up to request clarification or add additional context in comments.

2 Comments

I read the above used method here
You are using org.json.simple.JSONArray which doesn’t have this method. org.codehaus.jettison.json has getJSONObject

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.