如何在JSONObject / Array查找中查找值

时间:2015-07-20 02:33:12

标签: java android json jsonobject

以下是JSON Feed:

    {
"list" : { 
"meta" : { 
"type" : "resource-list",
"start" : 0,
"count" : 2
},
"resources" : [ 
{
"resource" : { 
"classname" : "Quote",
"fields" : { 
"name" : "USD/KRW",
"price" : "1151.295044",
"symbol" : "KRW=X",
"ts" : "1437357550",
"type" : "currency",
"utctime" : "2015-07-20T01:59:10+0000",
"volume" : "0"
}
}
}
,
{
"resource" : { 
"classname" : "Quote",
"fields" : { 
"name" : "SILVER 1 OZ 999 NY",
"price" : "0.067476",
"symbol" : "XAG=X",
"ts" : "1437169614",
"type" : "currency",
"utctime" : "2015-07-17T21:46:54+0000",
"volume" : "62"
}
}
}
,
{
"resource" : { 
"classname" : "Quote",
"fields" : { 
"name" : "USD/VND",
"price" : "21815.500000",
"symbol" : "VND=X",
"ts" : "1437357540",
"type" : "currency",
"utctime" : "2015-07-20T01:59:00+0000",
"volume" : "0"
}
}
}

]
}
}

如何查找符号为(“符号”:“XAG = X”)的JSON对象的“价格”。在这种情况下,答案是(“价格”:“0.067476”)。我需要以编程方式执行此查找,因为JSON比此处提供的更大,并且给予我的唯一参数将是“符号”。

这可能吗?任何有关如何执行此操作的详细帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

这是您的Json对象格式

enter image description here

试试这个以获得正确的结果 -

JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
  JSONObject resource = resources.getJSONObject(j).getJSONObject("resource");
  JSONObject fields = resource.getJSONObject("fields");
    if(fields.getString("symbol").equals("XAG=X")){
       System.out.println("Price of symbol(XAG=X) is"+ fields.getString("price"));
    }    
}

答案 1 :(得分:0)

假设内容代表json字符串

import org.json.JSONArray;
import org.json.JSONObject;

JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
    JSONObject resource =     resources.getJSONObject(j).getJSONObject("resource");
    JSONObject fields = resource.getJSONObject("fields");
    System.out.println(fields.get("symbol"));
    System.out.println(fields.get("price"));
}