Skip to content
Advertisement

How to map a JSON response to a Java class using Java 11 HttpClient and Jackson?

I’m new to the Java 11 HttpClient and would like to give it a try. I have a simple GET request that return JSON and I would like to map the JSON response to a Java class called Questionnaire.

I understand that I can turn the response out of box into a String or an input stream like this

JavaScript

How can I write something that converts the JSON string to my Questionnaire class like this?

JavaScript

I use Jackson to transform JSON into Java class instances. Is there Jackson support for the new Java standard HttpClient yet?

UPDATE 1 I was not precise enough, sorry about that. I am looking for a blocking get example. I was aware of http://openjdk.java.net/groups/net/httpclient/recipes.html#jsonGet

Advertisement

Answer

Solution for Java 11 HttpClient::sendAsync only

Based on this link you can do something like this :

JavaScript

I used some dummy endpoint which provides sample JSON input and sample model class to map the response directly to Model class using Jackson.

Solution for Java 11 HttpClient::send and HttpClient::sendAsync

I found a way by defining custom HttpResponse.BodyHandler :

JavaScript

Then I call it :

JavaScript

The response is :

JavaScript

The JavaDoc of HttpResponse.BodySubscribers::mapping was particulary useful to solve this. It can be further improved to use HttpResponse.BodySubscribers::ofInputStream instead of HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8) to define the BodySubscriber for the JsonBodyHandler.

Advertisement