I’ve run into an issue while building out my controller. I am sending a GET request to a third party and receiving back data that I then map to a DTO. One of those pieces of data is Address and AddressType.
I am calling a third party with a GET request using:
final ResponseEntity<AddressResponseDTO> response =
restTemplate.exchange(builder.build().toUri(),
HttpMethod.GET,
request,
AddressResponseDTO.class);
This is my Json Response:
"addressType": "Mailing",
"line1": "123 Ave",
"line2": "",
"city": "New York",
"state": "NY",
Originally, I am mapping these values using
@JsonProperty("addressType")
private AddressType addressType;
@JsonProperty("line1")
private String line1;
@JsonProperty("line2")
private String line2;
@JsonProperty("city")
private String city;
@JsonProperty("state")
private String state;
Address Type is an enum.
public enum AddressType {
BUSINESS,
MAILING,
DELIVERY
}
The problem is that the Json response returns Business instead of BUSINESS which throws an error.
I tried adding this to the DTO:
@JsonProperty("addressType")
private String addressEnum;
private AddressType addressType = AddressType.valueOf(addressEnum.toUpperCase());
But it just ignores this. Is there a simple way to map Business to BUSINESS? I feel like this should be a simple Springboot annotation but I can’t find anything.
2
Answers
A possible solution would be to create a custom deserializer using Jackson. This allows you to write custom code to perform the deserialization, giving you total control over how the data is interpreted.
First, define a new deserializer class
Then, in your DTO, use the @JsonDeserialize annotation to specify this new deserializer class
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
This code will now correctly deserialize any case variation of the AddressType enum values from the JSON response.
You’re most likely using Jackson for deserialization, which supports ignoring case on enums.
When initializing you
RestTemplate
, you can turn that feature on.