0

I am trying to fetch some date using a GET request towards an API. What I want to do is to save the response of this request as a Java class I have created beforehand. Here´s my class:

import java.util.List;
    
public class Person {
    String name = null;
    List<Siblings> siblings  = null;
}

And here´s how I am sending a GET request and reading data as String:

try {
    URL url = new URL("someURL");
    
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setRequestProperty("Authorization", "Bearer " + "bearerString");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    InputStream content = (InputStream) connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception e) {
    e.printStackTrace();
}

How can I save the response of the Http Request in a class object instead of just a String?

Nurio Fernández
  • 518
  • 5
  • 22
moirK
  • 651
  • 3
  • 11
  • 34

1 Answers1

1

You can use Jackson https://github.com/FasterXML/jackson

Example:

ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
Nurio Fernández
  • 518
  • 5
  • 22