8

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!!

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

How should I pass a string as a path parameter?
Path parameters are passed in via the .uri(URI.create(endpoint)) portion of your code. For example, with a path param called exampleId, your code would look like this .uri(URI.create("http://example.com/examples/ + exampleId)).
0

There are various approaches to your problem.

  1. Simplest: Use Gson, which can map a JSON response automatically to a given Object type (Instead of theJsonString you can also pass a InputStream or similar):
Gson gson = new GsonBuilder().create();
gson.fromJson(theJsonString, MyObject.class);
  1. Medium: What you are doing is already correct. You only need to parse the String you are getting to your MyObject.

  2. Hard: You can write your own HttpResponse.BodyHandler<MyObject>, which converts the response to a MyObject.

If you are able to use external libraries, definetly use Gson or similar.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.