Java中访问JSON嵌套值的动态方式

Sol*_*ake 3 java parsing android json multidimensional-array

我有这个 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"
                    }
                ]
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我用来访问徽章 -> 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有更好/更快或更动态的方式来使用 java/android 访问 JSON 嵌套属性?我正在使用 Gson 库来完成这项任务,并且不介意切换到任何其他解决方案以使其更容易,因为这是为了访问单个变量而编写的代码太多。

理想情况下,我正在寻找类似的东西:

String textColor = data.get("maindrawer").get("actions").get(1).get("badge").get("textColor");
Run Code Online (Sandbox Code Playgroud)

另外我现在对使用 POJO 不是很感兴趣。

最后,我还是 Java 新手,所以我可能在这里遗漏了一些东西,或者可能有一些限制?总之谢谢你的帮助!!

Sol*_*ake 6

使用JsonPath库找到了我需要的东西。看起来它与我需要的相似。这是我找到的示例代码:

String textColor = JsonPath.parse(json).read("$.maindrawer.actions[1].badge.textColor");
Run Code Online (Sandbox Code Playgroud)

非常干净和直接。希望这也能节省别人的时间。