0
{
  "hits": [
    {
      "name": "Google",
      "results": [
        {
          "count": 27495
        }
      ]
    },
    {
      "name": "Yahoo",
      "results": [
        {
          "count": 17707
        }
      ]
    }
}

i'am able to read the name and results from the above json by the below code, but unable to print the count value alone from JSON.

JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
    System.out.println("Inside IF...");
    JSONArray ja = (JSONArray) jsonObject.get("hits");
    for(int i=0;i<ja.size() ; i++)
    {
        System.out.println("Inside FOR...");
        JSONObject tempJsonObj = (JSONObject) ja.get(i);
        System.out.println(tempJsonObj.get("name").toString());
        System.out.println(tempJsonObj.get("results").toString());
    }
}

How to extract an array of JSON inside JSON array

2

1 Answer 1

2

Just as you parsed for Outer JSONArray (hits ) . Follow the same for inner ("results") :

JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
    if(null!=jsonObject.get("hits"))
    {
        System.out.println("Inside IF...");
        JSONArray ja = (JSONArray) jsonObject.get("hits");
        for(int i=0;i<ja.size() ; i++)
        {
            System.out.println("Inside FOR...");
            JSONObject tempJsonObj = (JSONObject) ja.get(i);
            System.out.println(tempJsonObj.get("name").toString());
            System.out.println(tempJsonObj.get("results").toString());
      JSONArray innerarray = (JSONArray) tempJsonObj.get("results");
    for(int i=0;i<innerarray.size() ; i++)
    {
     JSONObject tempJsoninnerObj = (JSONObject) innerarray.get(i);
            System.out.println(tempJsoninnerObj.get("count").toString());
    }


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

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.