繁体   English   中英

如何将http响应放入集合

[英]How to put http response into a Set

如何将http响应放入Employee类型的集合(集合集)中。

我正在获取数据作为HTTP响应,但是我必须将其放入Employee类型的set(Collection Set)中

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;
}

响应应保存在Set中

您可以使用库Jackson来将json解析为Set。

如果您先使用Maven导入依赖项

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

然后,您可以解析http响应,如下所示:

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

对象Employee需要准确地表示响应

这里有更多例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM