简体   繁体   中英

How to extract an array of JSON inside JSON array

{
  "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

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());
    }


        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM