簡體   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