Pulling out value of keys in JSON using Java, when key is under hierarchy

227 views Asked by At

I need to pull out value of RecordOne from following JSON.

{
  "errors": [],
  "data": {
    "paging": {
      "RecordOne": 8,
      "RecordTwo": 9,
      "recordThree": 2,
      "totalNumberOfRecords": 86052
    },
    "products": [
      {
        "testabstract": "test data",
        "authors": "Frank Jr.",
        "invertedauthors": "Frank VJr.",
        "formatCode": "KND"
      }
     ]
   }
}

I'm using Java as language and JSON object to achieve the same, following is what I'm using:

protected String getTokenValueUnderHeirarchy(String responseString){
        JSONObject json = new JSONObject(responseString);
        String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
        System.out.println("val::"+val);
return val;
    }

I'm getting value of val = 1, it should be 8

If I try to seek value for key totalNumberOfRecords with same code it returns correct value which is 86052

I know it's something silly but I can't catch it.

1

There are 1 answers

4
nadnavillus On

When I ran your code with the JSON example, I ended up with a "JSONException: JsonObject["RecordOne"] is not a string"..... which it isn't. Wrapping the 8 with double quotes: "8" returned the value that you expected. You can access this value with other get methods: getInt if you would like.

This test case parses both a String and an int. I pulled this from your example. Does it run for you?

package org.nadnavillus.test;

import org.json.JSONObject;
import org.junit.Test;

public class TestCase {

    protected String getTokenValueUnderHeirarchy(String responseString) throws Exception {
        JSONObject json = new JSONObject(responseString);
       String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
        System.out.println("val::"+val);
        return val;
    }

    protected String getTokenValueUnderHeirarchyInt(String responseString) throws Exception {
        JSONObject json = new JSONObject(responseString);
        int val= json.getJSONObject("data").getJSONObject("paging").getInt("RecordTwo");
        System.out.println("val::"+val);
        return String.valueOf(val);
    }

    @Test
    public void testJson() throws Exception {
        String input = "{\"errors\": [], \"data\": {\"paging\": {\"RecordOne\": \"8\", \"RecordTwo\": 9, \"recordThree\": 2, \"totalNumberOfRecords\": 86052}}}";
        String test = this.getTokenValueUnderHeirarchy(input);
        System.out.println(test);
        test = this.getTokenValueUnderHeirarchyInt(input);
        System.out.println(test);
    }
}