I have an API , which gives a JSON response like this
[{
"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"
}
}
}]
I want to find all the unique emp_type
attribute from this response. I tried the following approaches but none of them are working -
Approach -1
List<Map<String, String>> companies = response.jsonPath().getList("records");
System.out.println(companies.get(0));
Approach -2
List<Map<String, String>> companies = response.jsonPath().getList("records");
System.out.println(companies.get(0).get("emp_type"));
Approach -3
Map<String, String> company = response.jsonPath().getMap("records");
System.out.println(company.get("emp_type"));
Approach -4
String username = response.jsonPath().getString("records[0]");
System.out.println(username.indexOf(1));
Approach - 5
String value = response.path("records").toString();
System.out.println(value);
Edit -1 : Fixed the JSON.
You can try this way:
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);
}