2

I am using the Java HttpClient (java.net.http) and I am sending a GET request.

The response I get is a JSON String of the class "UserDto".

HttpResponse<String> send = httpClient.send(accept, HttpResponse.BodyHandlers.ofString());

I don't want to receive my response as a string but convert it directly into a "UserDto" object.

LeTest
  • 73
  • 7
  • 1
    Use Gson or Jackson to parse the received String. These libraries also provide methods to parse Json from an `InputStream` which is provided by every http client. – Robert Jan 18 '22 at 08:12

2 Answers2

3

You can use gson package to map the string to your UserDto class like the following:

String result;  // JSON String of the class "UserDto".
UserDto userDto = gson.fromJson(result, UserDto.class);
return userDto;

jackson is also an option but I prefer gson as its really simple to map with.

George
  • 2,292
  • 2
  • 10
  • 21
2

GSON can be use to convert a UserDTO to USER class

Ensure that you have the Gson library added to your project. If you are using Maven, you can include the following dependency in your pom.xml file:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Import the Gson library into your Java class:

import com.google.gson.Gson;

Create an instance of the Gson class:

Gson gson = new Gson();

Use the Gson instance to convert the UserDTO to a JSON string:

String json = gson.toJson(userDTO);

Assuming your UserDTO object is named userDTO, the toJson() method will convert the UserDTO object to a JSON string representation.

Convert the JSON string back to a User entity object:

User user = gson.fromJson(json, User.class);

This fromJson() method parses the JSON string and converts it into a User object of the specified class, which in this case is the User entity class. Make sure your User entity class has matching field names and types with the UserDTO class to ensure a successful conversion. By using Gson, you can easily convert between JSON and Java objects, simplifying the process of converting a UserDTO to a User entity class.