Android Json Parse
I have this json response: [{'id':'1','cat':'A','pic':'false','sector':'1'},{'id':'2','cat':'B','pic':'true','sector':'2'}] I need to parse it on android. I have trying follow cod
Solution 1:
You should use next code:
JSONArray jsonArray = newJSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));
Because you have not an object in json, but an array, so you should create array instead of object. And thats why your modification works. Because in modified code "data" is an object (JSONObject)
Solution 2:
JSONArray array = newJSONArray(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");
}
Or you can just use Gson Library. Just create your pojo classes
publicclassData{
int id;
String cat;
String pic;
String sector;
//setter and getter
}
then,
List<Data> datas = gson.fromJson(string_of_json_array, new TypeToken<List<Data>>(){}.getType());
for(Data item: datas){
String pic = item.getPic();
}
Post a Comment for "Android Json Parse"