Issue
I have to use the exchange() method because I pass HttpHeaders there.
ResponseEntity<WeatherResponse> response Entity = restTemplate.exchange(
weather UrlRequest, Http Method.GET, new HttpEntity<>(headers), WeatherResponse.class);
JSON:
{
"geoloc": {
"city": {
"id": 213,
"name": "Boston"
},
"country": {
"id": 213,
"name": "USA"
},
"temp": {
"value": 19.4
}
}
Object to deserialization:
class WeahterResponse{
String country;
String city;
float temp;
}
How to influence deserialization in this case. There are two objects in JSON, and I need one?
Solution
Thanks for João Dias. I made custom deserializer. https://www.baeldung.com/jackson-deserialization
In my case:
public class WeatherDeserializer extends JsonDeserializer<WeatherResponse> {
@Override
public WeatherResponse deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
JsonNode nodeTree = jsonParser.getCodec().readTree(jsonParser);
JsonNode geoObjectNode = nodeTree.get("geo_object");
JsonNode factNode = nodeTree.get("fact");
String country = geoObjectNode.get("country").get("name").textValue();
String province = geoObjectNode.get("province").get("name").textValue();
String locality = geoObjectNode.get("locality").get("name").textValue();
GeoObject geoObject = new GeoObject(country, province, locality);
Short temp = factNode.get("temp").shortValue();
Long obsTime = factNode.get("uptime").longValue();
return new WeatherResponse(geoObject,temp,obsTime);
}
}
@AllArgsConstructor
@Getter
@JsonDeserialize(using = WeatherDeserializer.class)
public class WeatherResponse {
private GeoObject geoObject;
private Short temp;
private Long uptime;
}
Answered By - Самый Важный
Answer Checked By - Mary Flores (JavaFixing Volunteer)