Android 如何从JSON中选择特定数据
我正在开发一个Android应用程序,我必须实现一个解析JSON并向我返回特定结果的函数 例如,我有一个JSON,其结构如下:Android 如何从JSON中选择特定数据,android,json,Android,Json,我正在开发一个Android应用程序,我必须实现一个解析JSON并向我返回特定结果的函数 例如,我有一个JSON,其结构如下: [ { "date":"17-06-2016", "desc":"My description", "id":"9", "img":"http:\/\/myurl\/pathimage\/image.jpg", "text":"Lorem Ipsum.", "title":"My ti
[
{
"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,但我不知道如何以编程方式选择JSON对象来区分id。
******编辑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);
}
JSONArray新闻请求;
试一试{
newsReq=newjsonarray(result.toString());
对于(int i=0;i
假设您像这样对JSON数组进行pasring
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
}
}
JSONArray JSONArray=新的JSONArray(响应);
for(int i=0;i
遍历所有对象并比较ID。不能只选择您不能选择的对象。正如@cricket_007所指出的,您唯一的选择是在对象上迭代测试id
参数,直到找到9
。想一想。除非你先读取值,否则你怎么知道一个值是“9”呢?你可以试试运气,没有任何保证,想想“程序员”现在发生了什么。。。“在集合中找到并返回具有给定谓词的项的实现函数”是当时的一个基本练习obj.getString(“id”)='9'
,这不是我们在Java中比较字符串的方式。在这种情况下,最好使用.equals(“9”)。是的,甚至更好的是“9.equals()