首页 > 解决方案 > 如何从以下 JSON 中提取和显示首选项节点

问题描述

JSON:

[
    {
        "name": "TEST",
        "desc": "",
        "descData": null,
        "closed": false,
        "idOrganization": null,
        "idEnterprise": null,
        "limits": null,
        "pinned": null,
        "shortLink": "0vww",
        "powerUps": [],
        "dateLastActivity": "2020-02-20T17:35:34.008Z",
        "idTags": [],
        "datePluginDisable": null,
        "creationMethod": null,
        "ixUpdate": null,
        "enterpriseOwned": false,
        "idBoardSource": "1232131",
        "id": "1231231123",
        "starred": false,
        "url": "test",
        "prefs": {
            "permissionLevel": "private",
            "hideVotes": false,
            "voting": "disabled",
            "comments": "members",
            "invitations": "members",
            "selfJoin": false,
            "cardCovers": true,
            "isTemplate": false,
            "cardAging": "regular",
            "calendarFeedEnabled": false,
            "background": "5c2f9de25f4d0845100f81b3",
            "backgroundImage": "TEST",
            "backgroundTile": false,
            "backgroundBrightness": "light",
            "backgroundBottomColor": "#635e5d",
            "backgroundTopColor": "#f4f4f3",
            "canBePublic": true,
            "canBeEnterprise": true,
            "canBeOrg": true,
            "canBePrivate": true,
            "canInvite": true
        },
        "subscribed": false,
        "labelNames": {
            "green": "",
            "yellow": "",
            "orange": "",
            "red": "",
            "purple": "",
            "blue": "",
            "sky": "",
            "lime": "",
            "pink": "",
            "black": ""
        },
        "dateLastView": "2020-05-24T20:26:00.621Z",
        "shortUrl": "https://trello.com",
        "templateGallery": null,
        "premiumFeatures": []
    }
]

尝试提取用户首选项节点时,以下代码失败 -

    System.out.println("User Preferences are below: \n");
    LinkedHashMap <String,String> tmplist = new LinkedHashMap<>();
    tmplist.putAll(js.get("prefs")); 
    Iterator<String> itr = tmplist.keySet().iterator();
    while (itr.hasNext()) 
    {
        String key = itr.next();
        System.out.println(key+""+tmplist.get(key));  // ---- Fails here. java.util.LinkedHashMap 
                                                    //cannot be cast to java.lang.String
    }

不想手动提取如下值 String colorblind = js.get("prefs.colorBlind").toString(); System.out.println("色盲为"+colorblind);

请建议我如何修复代码以便我可以提取完整的首选项。

标签: rest-assured-jsonpath

解决方案


你的 JSON 以 JSON 数组开头,所以当你使用“get”方法时,你会得到List<>一些东西。使用您的代码,您将获得List<LinkedHashMap<>>.

您不应该使用特定的地图实现。相反,您应该使用一个接口,以便 JsonPath 可以确定哪个地图实现是最好的,如下所示: List<Map<>>

另一件事是Map<>. prefsJSON 对象同时包含字符串和布尔值。当<String, String>您将自己暴露给ClassCastException. 相反,您应该使用Object并弄清楚它是哪种类型。

下面是如何打印出prefsJSON 对象的键和值的实现:

旧版本的 Java:

    List<Map<String, Object>> prefs = path.get("prefs");
    for (Map<String, Object> pref : prefs) {
      for (String key : pref.keySet()) {
        System.out.println(String.format("key: %s | value: %s", key, pref.get(key)));
      }
    }

从 Java 1.8 开始,我们可以使用 Streams

    List<Map<String, Object>> prefs = path.get("prefs");
    prefs.forEach(map -> map.forEach((key, value) -> System.out.println(String.format("key: %s | value: %s", key, value))));

推荐阅读