Issue
How to convert string to DTO.
I am doing some db fetch and getting String.
List<String> tempString = myRepo.getData(str);
I am getting string here like this
{"LastName": "Ben", "FirstName": "David", "EmailAddress": "[email protected]"}
now I want to convertto dto.
my dto will be like this.
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class UserDTO {
@JsonProperty("FirstName")
private String firstName;
@JsonProperty("LastName")
private String lastName;
@JsonProperty("EmailAddress")
private String email;
}
Now here is what I am trying but not getting sucees, anything I am missing here.
ObjectMapper mapper = new ObjectMapper();
UserDTO userdeto;
try{
userdeto= mapper.readValue(tempString.get(i), UserDTO.class);
}
but this is wrong here I. any other way to get this.
Solution
Using Java 8
It seems that you are getting list of String from the database, you can convert the list of string into list of UserDTO by this approach.
Approach Here:
Here I have stream
the list of string and convert each String
into UserDTO
type using the map()
operation and collecting it as a list of UserDTO.
where, tempString
is the list that you are preparing from the db (it is hardcoded in my case for the solution purpose)
public class Test {
public static void main(String[] args) {
List<String> tempString = new ArrayList<>();
tempString.add("{\"LastName\": \"Ben\", \"FirstName\": \"David\", \"EmailAddress\": \"[email protected]\"}");
tempString.add("{\"LastName\": \"Ben2\", \"FirstName\": \"David1\", \"EmailAddress\": \"[email protected]\"}");
tempString.add("{\"LastName\": \"Ben3\", \"FirstName\": \"David2\", \"EmailAddress\": \"[email protected]\"}");
ObjectMapper mapper = new ObjectMapper();
List<UserDTO> userDtoList = tempString.stream().map(x -> {
UserDTO userDto = null;
try {
userDto = mapper.readValue(x, UserDTO.class);
} catch (JsonProcessingException e) {
System.out.println("exception"+e);
}
return userDto;
}).collect(Collectors.toList());
System.out.println(userDtoList);
}
}
Output:
[UserDTO(firstName=David, lastName=Ben, [email protected]), UserDTO(firstName=David1, lastName=Ben2, [email protected]), UserDTO(firstName=David2, lastName=Ben3, [email protected])]
Answered By - IamGroot
Answer Checked By - Gilberto Lyons (JavaFixing Admin)