【发布时间】:2019-03-01 13:32:46
【问题描述】:
我有一个 API,它提供这样的 JSON 响应
[{
"records": {
"0": {
"id": 123,
"emp_type": "P",
"emp_level": "8",
"emp_id": "12345"
},
"1": {
"id": 132,
"emp_type": "Q",
"emp_level": "1",
"emp_id": "1234589"
},
"2": {
"id": 132,
"emp_type": "Q",
"emp_level": "1",
"emp_id": "1234589"
},
"3": {
"id": 134,
"emp_type": "Q",
"emp_level": "3",
"emp_id": "1231"
}
}
}]
我想从此响应中找到所有唯一的 emp_type 属性。我尝试了以下方法,但都没有奏效 -
方法-1
List<Map<String, String>> companies = response.jsonPath().getList("records");
System.out.println(companies.get(0));
方法-2
List<Map<String, String>> companies = response.jsonPath().getList("records");
System.out.println(companies.get(0).get("emp_type"));
方法-3
Map<String, String> company = response.jsonPath().getMap("records");
System.out.println(company.get("emp_type"));
方法-4
String username = response.jsonPath().getString("records[0]");
System.out.println(username.indexOf(1));
方法 - 5
String value = response.path("records").toString();
System.out.println(value);
编辑 -1 :修复 JSON。
【问题讨论】:
-
你总是引用路径
locations_data,它甚至不在你的json中。这应该如何工作? -
我现在已经修好了。请查看更新后的问题。
-
我不熟悉 JsonPath 但
records应该返回一个对象而不是字符串或字符串列表。假设它像其他 json 库一样工作,获取records.0.emp_type可能看起来像response.jsonPath().getMap("records").get("0").get("emp_type")。如果可行,您可以从那里开始工作,即遍历records中的所有元素并根据需要处理它们的emp_type。 -
它返回一个
java.util.ArrayList cannot be cast to java.util.Map错误 -
也许你可以试试这个 List
emp_types = Arrays.asList(response.jsonPath().getString("emp_type").split("\\s*,\\s*") );
标签: java rest-assured rest-assured-jsonpath