0

How can i put http response into a set(Collection Set) of Employee type.

I am getting data as HTTP response but i am have to put it inside a set(Collection Set) of Employee type

public Set<Employee> getAllEmployees() throws ServiceException {
    setOtherAppDetails();
    HttpStatus status = HttpStatus.OK;
    Set<Employee> employees = new HashSet<Employee>();
    try {
        System.out.println("Inside newly created DNG controller method");
        String postUrl = "http://localhost:8081/otherApp/empserv/list/dngEmployees";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(postUrl);
        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        System.out.println("responseBody =" +EntityUtils.toString(entity));
        // employees.add((Employee)response); wants to do something like this but its not working, sorry if it seems silly 
    }  catch (IOException exception) {
        exception.printStackTrace();
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }       
    return employees;
}

The response should be kept in Set

Peter Bagyinszki
  • 1,069
  • 1
  • 10
  • 29
Janny
  • 127
  • 1
  • 12

1 Answers1

1

You can use the library Jackson to parse a json as Set.

If you use Maven first import the dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9.2</version>
</dependency>

Then you can parse the http response as following:

ObjectMapper mapper = new ObjectMapper();
Set<Employee> myObjects = mapper.readValue(EntityUtils.toString(entity), new TypeReference<Set<Employee>>(){});

The object Employee need to be the exact rappresentation of the response

More examples here