JSON数组未被解析

时间:2016-01-08 06:39:35

标签: android json

我有这种格式的JSON响应:

{
    "success": true,
    "categories": [{
        "id": "774",
        "name": "1"
    }, {
        "id": "774",
        "name": "1"
    }]
}

我正在解析它:

try {
 JSONObject obj = new JSONObject(response);
 String success =  String.valueOf(obj.getBoolean("success"));

 JSONArray arr =  obj.getJSONArray("categories");
 //loop through each object
 for (int i=0; i<arr.length(); i++) {

   JSONObject jsonProductObject = arr.getJSONObject(i);
   String name = jsonProductObject.getString("name");
   String url = jsonProductObject.getString("id");
   Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
 }
} catch (JSONException e) {
   e.printStackTrace();
}

但我只能获得成功的价值。我在这里做错了什么?

3 个答案:

答案 0 :(得分:1)

更正json键

JSONArray arr = obj.getJSONArray(“checkouts”);

替换为:

JSONArray arr = obj.getJSONArray(“categories”);

答案 1 :(得分:1)

解析如下 -

JSONObject obj = new JSONObject(json);

String success =  obj.getString("success");
JSONArray arr =  obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {

    JSONObject jsonProductObject = arr.getJSONObject(i);
    String name = jsonProductObject.getString("name");
    String url = jsonProductObject.getString("id");

}

答案 2 :(得分:1)

这样做,

if (!result.equalsIgnoreCase("")) {
                try {
                JSONObject _jsonObject = new JSONObject(result);
                boolean json = false;

                    json = _jsonObject.getBoolean("Status");
                    JSONArray jsonArray1 =  _jsonObject.getJSONArray("categories");

                for (int i=0; i<jsonArray1.length(); i++) {

                    JSONObject jsonObject = jsonArray1.getJSONObject(i);
                    String name = jsonObject.getString("name");
                    String id = jsonObject.getString("id");

                }
                } catch (Exception e) {
                    Utils.printLoge(5, "error parse json", "--->" + e.getMessage());
                    return "ERROR";
                }
            }