如何将 http 响应放入 Set

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


我正在获取数据作为 HTTP 响应,但我必须将其放入员工类型的集合(集合集)中


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 中


PIPIONE
浏览 94回答 1
1回答

弑天下

您可以使用库 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 需要是响应的准确表示
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java