I have a Json array, i want to get only one Json object from it. In this example how can i get the object with Apple
[
{
"name": "mango",
"use": "DA",
"date": "2011-09-26",
"seed": "31341"
},
{
"name": "apple",
"use": "DA",
"date": "2011-09-26",
"seed": "31341"
},
{
"name": "berry",
"use": "DA",
"date": "2011-09-26",
"seed": "31341"
}
]
Previously i used to get it via it's index position but since json doesn't guarantee me order/arrangement that's why i need to specifically get one object without using the index method.
You can use a loop to iterate over every item in the JSONArray and find which JSONObject has the key you want.
private int getPosition(JSONArray jsonArray) throws JSONException {
for(int index = 0; index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
if(jsonObject.getString("name").equals("apple")) {
return index; //this is the index of the JSONObject you want
}
}
return -1; //it wasn't found at all
}
You could also return the JSONObject instead of the index. Just change the return type in the method signature as well:
private JSONObject getPosition(JSONArray jsonArray) throws JSONException {
for(int index = 0; index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
if(jsonObject.getString("name").equals("apple")) {
return jsonObject; //this is the index of the JSONObject you want
}
}
return null; //it wasn't found at all
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With