Iam triying to call external API from SpringBoot, once i recive the response im trying to save in a dto Object.
HistoricalApiResponse responseMap = restTemplate.getForObject(
url,
HistoricalApiResponse.class);
sample response in below formate
{
"personsData": {
"2023-02-27": [
{
"country": "INDIA",
"age": 19,
"updated_at": "2022-06-24T00:00:11.483Z"
},
{
"country": "UK",
"age": 29,
"updated_at": "2022-06-24T00:00:11.483Z"
}
],
"2023-02-25": [
{
"country": "JPY",
"age": 39,
"updated_at": "2022-06-24T00:00:11.483Z"
},
{
"country": "CHINA",
"age": 39,
"updated_at": "2022-06-24T00:00:11.483Z"
}
]
}
}
I have wrote HistoricalApiResponse class in below formate.
public class HistoricalApiResponse {
HistoricalData[] historicalData;
}
class HistoricalData{
List<Person> personsData;
}
class Person{
Integer age;
String country;
Date upatedAt;
}
Im getting below exception
Cannot deserialize value of type [LHistoricalData;
from Object value (token JsonToken.START_OBJECT
); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type [LHistoricalData;
from Object value (token JsonToken.START_OBJECT
)
I have tried by changing HistoricalData to list, map and other ways. but getting some other exception. Im not able to find excat java class for above response.
Can you guys please help what's the Structure of Response class for the JSON.
Your java class is not matching the json model. You need a "personData" object which looks like a map where the keys are Date objects and the values are List. This is how it worked for me:
public class HistoricalApiResponse {
public Map<Date, List<Person>> personsData;
}
public class Person {
public Integer age;
public String country;
@JsonProperty("updated_at") // needed for mapping
public Date upatedAt;
}
And here's how you can test it:
@Test
void test() throws JsonProcessingException {
String json = """
{
"personsData": {
"2023-02-27": [
{
"country": "INDIA",
"age": 19,
"updated_at": "2022-06-24T00:00:11.483Z"
},
{
"country": "UK",
"age": 29,
"updated_at": "2022-06-24T00:00:11.483Z"
}
],
"2023-02-25": [
{
"country": "JPY",
"age": 39,
"updated_at": "2022-06-24T00:00:11.483Z"
},
{
"country": "CHINA",
"age": 39,
"updated_at": "2022-06-24T00:00:11.483Z"
}
]
}
}
""";
var om = new ObjectMapper();
HistoricalApiResponse response = om.readValue(json, HistoricalApiResponse.class);
System.out.println(response);
}