我有一个 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。
最佳答案
您可以尝试以下方法:
JsonPath jsonPath = new JsonPath(json);
List<Map<String, Map<String, Object>>> list = jsonPath.getList("records");
Set<String> uniqueValues = new HashSet<>();
for (Map<String, Map<String, Object>> map : list) {
for (Map<String, Object> m : map.values()) {
uniqueValues.add(String.valueOf(m.get("emp_type")));
}
}
for (String unique : uniqueValues) {
System.out.println(unique);
}
关于java - 使用 Rest Assured 从 JSON API 获取唯一属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54945729/