0

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.

demouser123
  • 4,108
  • 9
  • 50
  • 82
  • 1
    You always refer to path `locations_data` which isn't even in your json. How should that work? – Thomas Mar 01 '19 at 13:36
  • I have fixed it now. Please see the updated question. – demouser123 Mar 01 '19 at 13:39
  • I'm not familiar with JsonPath but `records` should return an object and not a string or list of strings. Assuming it works like other json libraries, getting `records.0.emp_type` might look like `response.jsonPath().getMap("records").get("0").get("emp_type")`. If that works you can work from there, i.e. iterate over all elements in `records` and handle their `emp_type` as needed. – Thomas Mar 01 '19 at 13:45
  • It returns a `java.util.ArrayList cannot be cast to java.util.Map` error – demouser123 Mar 01 '19 at 13:57
  • Maybe you could try this List emp_types = Arrays.asList(response.jsonPath().getString("emp_type").split("\\s*,\\s*")); – NickAth Mar 01 '19 at 13:59
  • @NickAth no - it doesn't gives the correct result. It just returns the `records` – demouser123 Mar 04 '19 at 06:30
  • What do you mean "correct result"? If you want the unique emp_types only then convert the arraylist you obtain and convert to a Set List emp_types = Arrays.asList(response.jsonPath().getString("emp_type").split("\\s*,\\s*")); Set unique_emp_types = new HashSet(emp_types ); – NickAth Mar 04 '19 at 09:40

4 Answers4

2

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);
}
bhusak
  • 1,320
  • 1
  • 9
  • 19
1

As stated in the comments section, you can first get the "emp_type" values and then keep the unique. To do that you can do the following

Retrieve a list of emp_types from the JSON

List<String> emp_types = 
Arrays.asList(response.jsonPath().getString("emp_type").split("\\s*,\\s*")); 

Keep the unique values from the response

1) By converting the list into a HashSet (a set allows only unique values)

Set<String> unique_emp_types = new HashSet<String>(emp_types );

OR

if want to have your unique values into a list and you use Java 8 + you can make use of the Java Stream API

2) List<String> unique_emp_types = emp_types.stream().distinct().collect(Collectors.toList());

NickAth
  • 1,089
  • 1
  • 14
  • 35
0

try this code :

                try {   
                    URL url = new URL("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = read.readLine();
                    String json = "";
                    while(line!=null) {
                        json += line;
                        line = read.readLine();
                    }   

                    JSONArray jsonArray = new JSONArray(json);
                    for(int i=0; i<jsonArray.length(); i++) {

                       JSONObject a = jsonArray.getJSONObject(i);

                    }

                String a = jsonArray.toString();
                request.setAttribute("json",a);
                request.getRequestDispatcher("NewFile.jsp").forward(request, response);

            } catch (Exception e) {
                e.printStackTrace();
                out.write(e.toString());
            }

and in jsp file :

<script type="text/javascript"//-->
 var a='${json}';
 var test = '<%= (String) request.getAttribute("json") %>';
 
 var json =JSON.parse(test);

 var i;
 for (i = 0; i < json.length; i++) { 
  document.write( "<tr><td>"+json[i].id+"</td>");
  document.write("<td>"+ json[i].nm+"</td>");
  document.write("<td>" +json[i].cty+"</td>");
  document.write( "<td>"+json[i].hse+"</td>");
  document.write( "<td>"+json[i].yrs + "</td></td>");
  }
 
 </script>
Elio Lako
  • 1,333
  • 2
  • 16
  • 26
0

Try using:

List<String> empTypes = response.jsonPath().get("records.*.emp_type");
mmalk03
  • 26
  • 3