Iam坚持使用选项获取数组 我的json看起来像这样,
{
"data": [{
"id": "36",
"combo_items": {
"type": "",
"combo": [""]
}
}, {
"id": "14",
"combo_items": {
"type": "combo",
"combo": [{
"id": "12",
"name": ""
}, {
"id": "15",
"name": "test"
}]
}
},
}]}
我已经尝试过...... 喜欢这些
try {
JSONArray ja = response.getJSONArray("data");
for (int i = 0; i < ja.length(); i++)
{
jo = (JSONObject) ja.get(i);
String id = jo.getString("id");
JSONObject combo_items = jo.getJSONObject("combo_items");
String combo_type = combo_items.getString("type");
try {
JSONArray jsonArray = combo_items.getJSONArray("combo");
for (int ii =0; ii<jsonArray.length(); ii++){
jsonObject = (JSONObject) jsonArray.get(ii);
String combo_id = jsonObject.getString("id");
String combo_name=jsonObject.getString("name");
}
}catch (JSONException e){
e.printStackTrace();
}
如何从json数组中获取json对象,我试过方法显示一些错误 string canot可以转换为jsonobject 请帮忙。
答案 0 :(得分:1)
您可以尝试使用opt
代替get
并检查是否为空。
try {
JSONArray ja = response.optJSONArray("data");
if (ja == null) {
return;
}
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.optJSONObject(i);
if (jo == null) {
continue;
}
String id = jo.optString("id");
JSONObject combo_items = jo.optJSONObject("combo_items");
String combo_type = combo_items.optString("type");
try {
JSONArray jsonArray = combo_items.optJSONArray("combo");
if (jsonArray != null) {
for (int ii = 0; ii < jsonArray.length(); ii++) {
JSONObject jsonObject = jsonArray.optJSONObject(ii);
if (jsonObject == null) {
continue;
}
String combo_id = jsonObject.getString("id");
String combo_name = jsonObject.getString("name");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
}