簡體   English   中英

在Java中訪問JSON嵌套值的動態方法

[英]Dynamic way to access JSON nested values in Java

我有這個JSON對象:

{
    "maindrawer":
    {
        "enabled": true,
        "actions":
        [
            {
                "type": "Section",
                "title": "Section 1"
            },
            {
                "id": 1,
                "type": "Primary",
                "title": "Title 1",
                "badge":
                {
                    "enabled": false,
                    "value": 0,
                    "textColor": "#000000",
                    "badgeColor": "#ff0990"
                },
                "subActions":
                [
                    {
                        "id": 1,
                        "type": "Primary",
                        "title": "Sub Title 1"
                    }
                ]
            }
        ]
    }
}

這是我用來訪問徽章的代碼 - > textColor值:

public void loadJSONFromRaw(Context context, int id)
{
    json = null;
    try
    {
        //read and return json sting
        InputStream is = context.getResources().openRawResource(id);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");

        //convert json to object
        Type type = new TypeToken<Map<String, Object>>() {}.getType();
        Map<String, Object> data = new Gson().fromJson(json, type);

        //access maindrawer property
        Map<String, Object> maindrawer = (Map<String, Object>)data.get("maindrawer");

        //access actions list
        List<Object> actions = (List<Object>)maindrawer.get("actions");

        //return first item in the list
        Map<String, Object> action = (Map<String, Object>) actions.get(1);

        //return badge object
        Map<String, String> badge = (Map<String, String>) action.get("badge");

        //access badge -> textColor value
        String textColor = badge.get("textColor");
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

是否有更好/更快或更動態的方式來使用java / android訪問JSON嵌套屬性? 我正在使用Gson庫來執行此任務,並且不介意切換到任何其他解決方案以使其更容易,因為這只是為了訪問單個變量而編寫的代碼太多。

理想情況下,我正在尋找類似的東西:

String textColor = data.get("maindrawer").get("actions").get(1).get("badge").get("textColor");

此外,我對使用POJO不是很感興趣。

最后,我還是Java的新手,所以我可能在這里遺漏了一些東西,或者有一些限制? 無論如何,謝謝你的幫助!!

使用JsonPath庫找到了我需要的東西 看起來它與我需要的相似。 這是我找到的示例代碼:

String textColor = JsonPath.parse(json).read("$.maindrawer.actions[1].badge.textColor");

非常干凈和直截了當。 希望這也能節省別人的時間。

由於您在本地訪問json文件,這意味着您知道它的結構。 所以不要使用 - Map<String, Object> data = new Gson().fromJson(json, type);

你可以使用這樣的東西 -

Map<String, MainDrawer> data = new Gson().fromJson(json, type);

其中MainDrawer是一個具有成員變量的類 - enabledactions和另一種類型的數組。

這將更容易獲取您的值,如使用 - mainDrawer.isEnabled()

這里有兩個解決方案,無需導入新庫。

編寫一個簡單的路徑解析器:

String textColor = (String)parse(data, "maindrawer", "actions", 1, "badge", "textColor");

//...

static Object parse(Object root, Object... params) {
    Object current = root;
    for (Object p : params) {
        if (p instanceof Number) {
            current = ((List<?>)current).get(((Number)p).intValue());
        } else {
            current = ((Map<?,?>)current).get(p.toString());
        }
    }
    return current;
}

或者解析並瀏覽Gson的JsonElement

JsonElement root = new Gson().fromJson(json, JsonElement.class);
String textColor = root
        .getAsJsonObject().get("maindrawer")
        .getAsJsonObject().get("actions")
        .getAsJsonArray().get(1)
        .getAsJsonObject().get("badge")
        .getAsJsonObject().get("textColor")
        .getAsString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM