1

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?

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
SaKH
  • 163
  • 1
  • 1
  • 13
  • 2
    Messy, unreadable code. The exception tells you the line number at which you get the NPE. Open a text editor, display line numbers, go to the line cited by the stack trace, and look at the references. One of them is null. A spin through a debugger will tell you faster than asking here. – duffymo Aug 17 '17 at 09:36
  • Use: `j.getJsonArray("questions");` without the cast instead of just `(...) j.get(...);`. There are better functions that will give you the right object: http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html, so casting is not necessary. – Andre Kampling Aug 17 '17 at 09:38
  • @AndreKampling thank you for your comment but am using org.json.simple so getJsonArray("") not possible! – SaKH Aug 17 '17 at 09:48

1 Answers1

0

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");
Yazan
  • 6,074
  • 1
  • 19
  • 33