将输入流转换为对象列表

Dhi*_*aja 2 inputstream list jackson apache-httpclient-4.x

我必须制作一个 jar 来点击 API 来获取人员详细信息列表,该列表基本上有四个字段:id、name、salary、department。

我正在使用 apache httpclient 执行 get 请求,该请求在点击 API 时为我提供了 httpentity。

httpentity提供了一个获取response内容的方法,但它返回的是inputstream。

在通过 inputreader 读取此输入流并将其打印出来时,我确认它为我提供了人员详细信息列表。

但我不知道如何将其转换为人员详细信息列表。

那是 PersonDetails 对象:-

    public class PersonDetails {
        private UUID id;
        private String name;
        private String department;
        private Integer salary;
    
        public UUID getId() {
            return id;
        }
    
        public void setId(UUID id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDepartment() {
            return department;
        }
    
        public void setDepartment(String department) {
            this.department = department;
        }
    
        public Integer getSalary() {
            return salary;
        }
    
        public void setSalary(Integer salary) {
            this.salary = salary;
        }
    
        @Override
        public String toString() {
            return "PersonDetails{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", department='" + department + '\'' +
                    ", salary=" + salary +
                    '}';
        }
    
}
Run Code Online (Sandbox Code Playgroud)

这是我的 GetRequest 代码:-

    public static void main(String[] args) {
            List<PersonDetails> personDetails = new ArrayList<>();
            HttpClient httpClient = HttpClientBuilder.create().build();
            String url = "/api/person-details";
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                InputStream content = httpEntity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Run Code Online (Sandbox Code Playgroud)

我想将此内容转换为人员详细信息列表。

有人可以帮助我吗?我听说过杰克逊,但我不知道如何使用它。

Dhi*_*aja 5

首先我创建一个默认集合类型

CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, PersonDetails.class);

List<PersonDetails> personDetails = mapper.readValue(content,collectionType);
Run Code Online (Sandbox Code Playgroud)

其中内容是输入流。我在某人的博客上找到的。