I have JSON some thing like below
JavaScript
x
{
"title": "seller_information",
"sellers": [
{
"seller": "s1",
"prod_on_sale": "flowers"
},
{
"seller": "s2",
"prod_on_sale": "pet_food"
},
{
"seller": "s3",
"prod_on_sale": "vegatables"
}
]
}
I am aware how to iterate through JSON Array based on key and extract the values of that particular key. But stuck with one scenario let say instead of key i have value with if i have value ‘s1’ with me i want to traverse through above JSON and if it matches with any value i want to extract the complete JSON related to that value ‘s1’ like below
JavaScript
{
"seller": "s1",
"prod_on_sale": "flowers"
}
Please suggest some idea how can i do this i am newbie to JSON. Thanks in advance.
Advertisement
Answer
JavaScript
public static JSONObject getObject(String itemToSearch, JSONArray array) {
for(int i = 0; i < array.length(); i++) {
try {
JSONObject jsonObject = array.getJSONObject(i);
if (jsonObject.getString("seller").equals(itemToSearch)){
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
you can use this function by sending array of sellers from your JSON
JavaScript
sellersArray = yourJSON.getJSONArray("sellers");