7

I've decided on using JSON.Simple to parse Java in my application, as apposed to GSON or Jackson, because both of them seem over complicated for my needs and appeared to need additional class files to work as intended. I have the following JSON:

{
    "request":{
        "act":"rec_load_all",
        "email":"Redacted",
        "tkn":"Redacted",
        "a":"rec_load_all",
        "z":"Redacted"
    },
    "response":{
        "recs":{
            "has_more":false,
            "count":9,
            "objs":[{
                "rec_id":"1385442465",
                "rec_hash":"1825780e334bcd831034bd9ca62",
                "zone_name":"Redacted",
                "name":"Redacted",
                "display_name":"Redacted",
                "type":"A",
                "prio":null,
                "content":"Redacted",
                "display_content":"Redacted",
                "ttl":"1",
                "ttl_ceil":86400,
                "ssl_id":null,
                "ssl_status":null,
                "ssl_expires_on":null,
                "auto_ttl":1,
                "service_mode":"1",
                "props":{
                    "proxiable":1,
                    "cloud_on":1,
                    "cf_open":0,
                    "ssl":0,
                    "expired_ssl":0,
                    "expiring_ssl":0,
                    "pending_ssl":0,
                    "vanity_lock":0
                }
            }]
        }
    },
    "result":"success",
    "msg":null
}

The objs array lists 9 different items, but I only included one for simplicity. I need to get has_more, count, and the id within objs. I've tried:

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(responseString);
JSONArray objs = (JSONArray) jsonObject.get("objs");
Iterator<JSONObject> iterator = objs.iterator();
while (iterator.hasNext()) {
    JSONObject idObj = (JSONObject) iterator.next();
    String id = (String) idObj.get("rec_id");
    System.out.println(id);
}

But it fires a java.lang.NullPointerException error, so I'm assuming because it's nested under response -> recs -> objs it isn't getting a value. I'm also following a few year old tutorial, so something could have changed since. If you could explain whats wrong and an example of how to fix it, I would greatly appreciate it, I learn by seeing.

EDIT: Full error

Exception in thread "main" java.lang.NullPointerException
    at ddns.Net.getId(Net.java:46)
    at ddns.DDNS.main(DDNS.java:7)
Java Result: 1

ddns.Net.getId(Net.java:46) | Iterator<JSONObject> iterator = objs.iterator(); ddns.DDNS.main(DDNS.java:7) | Just calls the method

6
  • can you provide the stacktrace? Commented Jul 19, 2014 at 15:12
  • @GaneshChithambalamA.S. Added it to the OP. Commented Jul 19, 2014 at 15:18
  • If it is throwing an NPE, then that means that idObj object might be null. It would be strange for get to throw NPE. It might return null but I wouldn't expect it to throw NPE. Commented Jul 19, 2014 at 15:23
  • I don't see id there in the JSON. Are you trying to get rec_id? Commented Jul 19, 2014 at 15:29
  • From the json you posted, the first object in the "objs" array doesnt seems to have "id" Commented Jul 19, 2014 at 15:30

2 Answers 2

7

You have to take any json object from parent and so on, take a look this code (I tried and works):

    public static void main(String[] args) throws IOException, ParseException {

    JSONParser jsonParser = new JSONParser();

    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("json.json");
    InputStreamReader reader = new InputStreamReader(is);
    JSONObject result = (JSONObject) jsonParser.parse(reader);
    JSONObject response = (JSONObject) result.get("response");
    JSONObject recs = (JSONObject) response.get("recs");

    boolean hasMore = (Boolean) recs.get("has_more");
    JSONArray objs = (JSONArray) recs.get("objs");
    System.out.println(recs);
    System.out.println("has more " + hasMore);

    Iterator objIter = objs.iterator();
    int i = 0;
    while (objIter.hasNext()) {
        i++;
        System.out.println(String.format("obj %d: %s", i, objIter.next()));
    }

}

There is another way that for me is easier and is to create a Java Bean with the same structure so... you will parse a hole object, if you are interested on this approach let me know.

Sign up to request clarification or add additional context in comments.

6 Comments

For learning purposes, if you'd like to provide both approaches that would be great.
I'm having an issue with your code. Exception in thread "main" java.lang.NullPointerException at java.io.Reader.<init>(Reader.java:78) at java.io.InputStreamReader.<init>(InputStreamReader.java:72) at ddns.Net.getId(Net.java:46) at ddns.DDNS.main(DDNS.java:7) Java Result: 1
My example reads from a local file called json.json, for your test use your parser instead of mine. So... copy my code from line JSONObject result = (JSONObject) jsonParser.parse(reader);, but instead of (reader) put (inputString).
To parse an object you could use Jackson so you could forget about parsing manually.
Wow, sorry about that. I completely ignored the first few lines assuming they were the same. It appears to be working now. I took a look at Jackson but it seemed too complicated. If you want to provide and example with that, then go ahead. I don't expect you to code the program for me though.
|
0

@Carlos Verdes pointed me in the right direction.

From the larger JSON I want put the name of the league, My_League, in a string because its different for each user.

JSON Snippet shortened for brevity:

{..."name":"Some_Dude", ... ,"expLevel":221,"league":{"id":12345,"name":"My_League","iconUrls":...},...}

Multiple occurrences of the key "name" exist in the JSON and if you look for key "name" again JSON.Simple just retrieves the first occurrence of "name" which would be "Some_Dude" thats right at the beginning.

So to get around that I set that section of the JSON, key "league", into a JSON object and then extracted key "name" from the object to get "My_League" for my string.

JSONObject leagueObj = (JSONObject) each.get("league");
String league = (String)leagueObj.get("name");

The key take away is that when you extract "league": you will get everything after : including all things between {..} up to the next , that is outside the closing curly }. Which, in my case, is more than you need leaving you to have parse that smaller section, hence the JSON Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.