SaKH SaKH - 1 year ago 106
Java Question

How to Read JSON From File in Java - json.simple

I am having troubles with reading a Json file in Java.

this is a Json file with content in this format:

{
"id": "10",
"groups": [{
"name": "text",
"questions": [{
"value": "text"
"response": {

}
}
]}
]}


What I've done in Java:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/test.json"));
JSONObject j = (JSONObject) obj;
System.out.println(j);
String id = (String)j.get("id");
int idpart = Integer.parseInt(id);
System.out.println("id :" + idpart);


JSONArray lg = (JSONArray) j.get("groups");
Iterator i = lg.iterator();
while (i.hasNext()) {
JSONObject gobj = (JSONObject) i.next();
String name = (String)gobj.get("name");
System.out.println(name);

/** The problem start from here !**/
JSONArray lq = (JSONArray) j.get("questions");
Iterator it = lq.iterator();
while (it.hasNext()) {
JSONObject qobj = (JSONObject) i.next();
String idQuestion = (String)qobj.get("id");
System.out.println(idQuestion);
//How to get responses ?
}
}


My question is how to get the response object from questions list?

When I tried to get questions list of object like this:

JSONArray lq = (JSONArray) j.get("questions");
Iterator it = lq.iterator();
while (it.hasNext()) {
JSONObject qobj = (JSONObject) i.next();
String idQuestion = (String)qobj.get("id");
System.out.println(idQuestion);
}


it shows me Error:
Null pointer
!

Could someone help me?

Answer Source

you have to get questions from lg not from j you are using Iterator, assigning a group object into gobj so use it:

JSONArray lq = (JSONArray) gobj.get("questions");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download