我正在开发一个Android应用程序,我必须实现一个解析我的JSON并返回给我某些结果的函数。
例如,我有一个带有此strcutures的JSON:
[
{
"date":"17-06-2016",
"desc":"My description",
"id":"9",
"img":"http:\/\/myurl\/pathimage\/image.jpg",
"text":"Lorem Ipsum.",
"title":"My title"
}, {
"date":"14-06-2015",
"desc":"My description 2",
"id":"5",
"img":"http:\/\/myurl\/pathimage\/image.jpg",
"text":"Lorem Ipsum 2.",
"title":"My title 2"
}
]
我只需要选择id = 9的对象,我该怎么做? 我如何以编程方式选择JSON对象区分尊重id?
我知道如何解析JSON,但我不知道如何以编程方式选择区分ID的JSON对象。
******编辑1 ******
JSONArray newsReq;
try {
newsReq = new JSONArray(result.toString());
for (int i = 0; i < newsReq.length(); i++) {
try {
if(obj.getInt("id")=='9'){
JSONObject obj = newsReq.getJSONObject(i);
obj.getString("img");
obj.getInt("id");
obj.getString("title");
}
} catch (JSONException e) {
Log.wtf("BulgariLog: ", e);
}
}
} catch (JSONException e) {
Log.wtf("BulgariLog: ", e);
}
答案 0 :(得分:0)
假设您正在像这样粘贴JSON数组,
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// get the id of current JSON object
String id = jsonObject.getString("id");
// check if the id matches with your required id
if (id.contains("9")) {
// the JSON object matches with your desired one
// get the remaining values here
} else {
// skip the object since it doesn't matches your given id
}
}