Search code examples
listjacksoninputstreamapache-httpclient-4.x

Convert inputstream to list of Objects


I have to make a jar to hit an API to get List Of Person-Details which basically has four fields :- id,name,salary,department.

I am using apache httpclient to do a get request which gives me an httpentity on hitting an API.

httpentity provides a method to get the content of response but it returns inputstream.

On reading this inputstream through inputreader and printing it out i am confirming that it is giving me a list of persondetails .

but i don't know how to convert it to list of persondetails.

That's PersonDetails Object :-

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

Thats my GetRequest Code :-

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

I want to convert this content to list of person details.

Could AnyOne Help Me? I have heard of Jackson but i don't know how to use it.


Solution

  • Firstly I Create A Default Collection Type

    CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, PersonDetails.class);
    
    List<PersonDetails> personDetails = mapper.readValue(content,collectionType);
    

    Where content is the inputStream. I found it on someone's blog.