简体   繁体   中英

How to parse a JSON Object to get an Array with in Array?

This is my JSON output. I am trying to return the "id": "9040" from instructions but am having trouble

{
  "packages": [
    {
      "instructions": [
        {
      "id": "9040",
      "fn": "test.xml",
      "@type": "down",
      "fp": ""
    }
  ],
  "id": "47968",
  "time": 1396036698630,
  "priority": 0
}

] }

Here is my code that returns the "Package" -> "Id"

         JSONObject jObject = new JSONObject(json);
         JSONArray jsonMainNode = jObject.optJSONArray("packages");
         int lengthJsonArr = jsonMainNode.length();  
         for(int i=0; i < lengthJsonArr; i++) 
         {
             /****** Get Object for each JSON node.***********/
             JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
             fileid  = Integer.parseInt(jsonChildNode.optString("id").toString());
             if (fileid > 0 )

             Log.i("JSON parse", "id = "+ fileid);
        }

Any help would be much appreciated.

Thank you

You forget about JSONArray instructions

    {
    "packages": [
        {
            "instructions": [
                {
                    "id": "9040",
                    "fn": "test.xml",
                    "@type": "down",
                    "fp": ""
                }
            ],
            "id": "47968",
            "time": 1396036698630,
            "priority": 0
        }
    ]
}

To parse

JSONObject jObject = new JSONObject(json);
JSONArray jsonMainNode = jObject.optJSONArray("packages");
JSONObject jb = (JSONObject) jsonMainNode.get(0);
JSONArray instructions = jb.getJSONArray("instructions");
JSONObject jb1 =  (JSONObject) instructions.get(0);
String id = jb1.getString("id");

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