Finding deeply nested key/value in JSON

前端 未结 2 1820
猫巷女王i
猫巷女王i 2021-01-06 22:48

Suppose I have a JSON array like this:

[
    {
        \"id\": \"429d30a1-9364-4d9a-92e0-a17e00b3afba\",
        \"children\": [],
        \"parentid\": \"\"         


        
相关标签:
2条回答
  • 2021-01-06 22:57

    You can use recursion to solve the problem of unlimited nesting. With Gson, it would be something like the following code snippet (not tested). Other libraries will provide structures as JsonElement as well.

    private JsonElement findElementsChildren(JsonElement element, String id) {
        if(element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();
            if(id.equals(jsonObject.get("id").getAsString())) {
                return jsonObject.get("children");
            } else {
                return findElementsChildren(element.get("children").getAsJsonArray(), id);
            }
        } else if(element.isJsonArray()) {
            JsonArray jsonArray = element.getAsJsonArray();
            for (JsonElement childElement : jsonArray) {
                JsonElement result = findElementsChildren(childElement, id);
                if(result != null) {
                    return result;
                }
            }
        }
    
        return null;
    }
    
    0 讨论(0)
  • 2021-01-06 23:00

    Based on Stefan Jansen's answer I made some changes and this is what I have now:

    nestedChildren declared globaly, and before the children are searched reset to new ArrayList()

    private void findAllChild(JSONArray array) throws JSONException {
    
        for ( int i=0;i<array.length();i++ ) {
            JSONObject json = array.getJSONObject(i);
            JSONArray json_array = new JSONArray(json.getString("children"));
            nestedChildren.add(json.getString("id"));
            if ( json_array.length() > 0 ) {
                findAllChild(json_array);
            }
        }
    }
    

    This assumes it is all Arrays, witch in my case it is

    0 讨论(0)
提交回复
热议问题