这是我的JSON输出。我正在尝试从说明中返回“ id”:“ 9040”,但遇到了麻烦

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


]
}

这是我的代码,返回“ 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);
        }


任何帮助将非常感激。

谢谢

最佳答案

您忘了JSONArray指令

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


解析

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");

07-24 16:55
查看更多