rest-assured-jsonpath - 如何从以下 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);
请建议我如何修复代码以便我可以提取完整的首选项。
解决方案
你的 JSON 以 JSON 数组开头,所以当你使用“get”方法时,你会得到List<>
一些东西。使用您的代码,您将获得List<LinkedHashMap<>>
.
您不应该使用特定的地图实现。相反,您应该使用一个接口,以便 JsonPath 可以确定哪个地图实现是最好的,如下所示:
List<Map<>>
另一件事是Map<>
. prefs
JSON 对象同时包含字符串和布尔值。当<String, String>
您将自己暴露给ClassCastException
. 相反,您应该使用Object
并弄清楚它是哪种类型。
下面是如何打印出prefs
JSON 对象的键和值的实现:
旧版本的 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))));
推荐阅读
- vue.js - 如何在 Vue 中使用 SVG 版本的 Twemoji?
- html - Chrome 忽略 aria-labelledby
- excel - VBA宏计时器作为函数()而不是子() - 丢失第一个变量
- javascript - 如何在不导入的情况下将不同的外部图像用于wordpress
- c++ - 在 capnproto RPC 中识别调用者
- python - Html 模板不会从 Flask 呈现。SystemError:没有设置异常的错误返回
- python - 导入与Django一致的mongodb dump
- javascript - 动态启用/禁用 kendo ui 控件
- javascript - 带有必需参数的打字稿解构
- java - 导航组件:从全局操作传递参数会导致 NullPointerException