Reputation: 1092
Below is the 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"
}
}
}
]
}
}
How do I go about finding the "price" of the JSON object who's symbol is ("symbol" : "XAG=X") for example. In this case the answer is ("price" : "0.067476"). I need to perform this lookup programatically since the JSON is rather larger than the one presented here and the only parameter given to me will be the "symbol".
Is this possible? Any detailed help on how to do this would be greatly appreciated.
Upvotes: 0
Views: 7634
Reputation: 326
This is your Json object Format
Try this for getting correct result -
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"));
}
}
Upvotes: 1
Reputation: 1083
Assuming content represents the json string
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"));
}
Upvotes: 0