0

I am trying to parse a nested JSON as shown below:

{
    "a":{"aa":"11","bb":"232"},
    "b":{"aa":"111","bb":"224"},
    "c":{"aa":"121","bb":"232"}
}

I am trying to get to the nested JSON part using loops:

JSONParser parser = new JSONParser();
JSONObject infoJSON = (JSONObject) parser.parse(new FileReader(new File("resources/abc.json")));                

for(int i=0 ;i< infoJSON.size(); i++){          
    JSONObject innerJSON = (JSONObject) infoJSON.get(i);            
    System.out.println(innerJSON.keySet());
}

It throws me NullPointerException. I feel there is some issue with the iteration.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
Betafish
  • 1,212
  • 3
  • 20
  • 45
  • Its not about "Null Pointer Exception". My question was on why is it not parsing the nested part – Betafish Apr 17 '17 at 06:43
  • Sometimes questions get closed by mistake. You're getting `null` because `size()` represents the count of objects in a JSON object which is a `Map` itself, so that's why `get(i)` does not make sense (`0` where only `a`, `b`, and `c` exist). This is what you need: `JSONObject infoJson = (JSONObject) parser.parse(reader); for ( Entry e : infoJson.entrySet() ) { JSONObject innerJson = (JSONObject) e.getValue(); System.out.println(innerJson.keySet()); }` – Lyubomyr Shaydariv Apr 17 '17 at 07:23
  • @LyubomyrShaydariv: any reason you haven't posted that as an answer? – Luke Woodward Apr 17 '17 at 07:42
  • @LukeWoodward The question is closed, so no answers can be posted, but I think the OP will read the comment. This is fine. I think the question might be re-closed again because the OP made a too common mistake while getting the `JSONObject` values that are actually `Map`s if the OP is using the JSON Smart library (and I believe the OP is). – Lyubomyr Shaydariv Apr 17 '17 at 07:50
  • I solved it looping through the keyset `for(Object key: infoJSON.keySet()){ JSONObject innerJSON = (JSONObject) infoJSON.get(key); )` – Betafish Apr 17 '17 at 07:59

1 Answers1

-2

Your code loops for the outer objects which will cause null pointer. Your code should looks like:

JSONParser parser = new JSONParser();
        JSONObject infoJSON = (JSONObject) parser.parse(new FileReader(new File("resources/abc.json")));                
 for(int j=0; infoJSON.size(); j++){
     for(int i=0 ;i< infoJSON.get(j).size(); i++){          
        JSONObject innerJSON = (JSONObject) infoJSON.get(j);            
        System.out.println(innerJSON.keySet());
    }
 }
Fady Saad
  • 1,169
  • 8
  • 13