Android JSON Parse

时间:2017-04-20 20:12:23

标签: android json

我有这个json回复:

[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]

我需要在android上解析它。

我尝试按照代码:

JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("");
JSONObject jsonObject = jsonArray.getJSONObject(0);

Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));

但它不起作用。

如果我的结果是:

{ "data":[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]}

我修改了以下代码:

JSONArray jsonArray = obj.getJSONArray("data");

有效。

我如何解析它考虑了我的第一个json响应(没有“数据”)

谢谢。

2 个答案:

答案 0 :(得分:2)

您应该使用下一个代码:

JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);

Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));

因为你没有json中的对象,而是一个数组,所以你应该创建数组而不是对象。这就是为什么你的修改工作。因为在修改后的代码"数据"是一个对象(JSONObject)

答案 1 :(得分:0)

JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    id = row.getInt("id");
    pic = row.getString("pic");
}

或者您可以使用Gson Library。只需创建你的pojo类

public class Data{
     int id;
     String cat;
     String pic;
     String sector;

     //setter and getter
}

然后,

List<Data> datas = gson.fromJson(string_of_json_array, new TypeToken<List<Data>>(){}.getType());
for(Data item: datas){
     String pic = item.getPic();
}