Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map HttpResponse in a Object Java

I'm making a GET REST call via HttpClient:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(endpoint))
    .GET()
    .header("Authorization", authHeader)
    .header("Content-Type", "application/json")
    .build();

HttpResponse<String> response = client.send(
    request, HttpResponse.BodyHandlers.ofString());

How can I map the response in the MyObject object? Is it correct to intercept it as a String first? also, I would need to pass a string as a path parameter, but I don't know where to add it.

Thanks for the support!!

like image 416
Prodox21 Avatar asked Jun 28 '26 11:06

Prodox21


1 Answers

Another commonly used library for this is Jackson ObjectMapper. Using ObjectMapper, you can map the body to an object like this:

String json = response.body(); // "{ \"name\" : \"Nemo\", \"type\" : \"Fish\" }";
Animal nemo = objectMapper.readValue(json, Animal.class);

For a step by step guide, see https://www.baeldung.com/jackson-object-mapper-tutorial#2-json-to-java-object

like image 102
Steve Avatar answered Jun 30 '26 00:06

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!