Java 从 JsonArray 中获取一个 JSONObject

Ced*_*oza 4 java json

我有一个 Json 数组,我只想从中获取一个 Json 对象。在此示例中,我如何使用 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"
}
]
Run Code Online (Sandbox Code Playgroud)

以前我曾经通过它的索引位置获取它,但由于 json 不保证我的订单/安排,这就是为什么我需要专门获取一个对象而不使用索引方法。

jay*_*j95 7

您可以使用循环遍历 JSONArray 中的每个项目并找到哪个 JSONObject 具有您想要的键。

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
    }
Run Code Online (Sandbox Code Playgroud)

您还可以返回 JSONObject 而不是索引。只需更改方法签名中的返回类型:

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
    }
Run Code Online (Sandbox Code Playgroud)