Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get one JSONObject from a JsonArray

Tags:

java

json

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.

like image 730
Ceddy Muhoza Avatar asked Feb 08 '23 18:02

Ceddy Muhoza


1 Answers

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
    }
like image 54
jaytj95 Avatar answered Feb 12 '23 10:02

jaytj95