I am new to Spring Boot and APIs, I am working on a project where I need to fetch data from public API and store it to the local database, though my spring boot application is connected with MySQL database. While fetching the data from the API, my compiler is throwing an exception saying :
Error while extracting response for type [class com.currencyExchangeRates.models.CurrencyDTO] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.currencyExchangeRates.models.CurrencyDTO` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.currencyExchangeRates.models.CurrencyDTO` out of START_ARRAY token at [Source: (PushbackInputStream); line: 1, column: 1]
My general idea is to get data from public API store it on the local database and then use those data according to my project requirements.
I have tried almost every solution from Google as well as from Stack Overflow but I am not getting any idea.
JSON format I am trying to fetch:
[
{
"table":"A",
"no":"237/A/NBP/2019",
"effectiveDate":"2019-12-09",
"rates":[
{
"currency":"bat (Tajlandia)",
"code":"THB",
"mid":0.1277
},
{
"currency":"dolar amerykański",
"code":"USD",
"mid":3.8704
}
]
}
]
Here, my CurrencyDTO class:
public class CurrencyDTO {
private String table;
private String num;
private String date;
private Rates rates;
// Getters and Setters, No-arg/arg constractor
Rates.java
public class Rates {
private String currency;
private Map<String, Double> price;
// Getters and Setters, No-arg/arg constractor
Piece of code where I call API :
try {
RestTemplate restTemplate = new RestTemplate();
CurrencyDTO forObject =
restTemplate.getForObject("http://api.nbp.pl/api/exchangerates/tables/a/", CurrencyDTO.class);
forObject.getRates().getPrice().forEach((key, value) -> {
Currency currency = new Currency(key, value);
this.currencyRepository.save(currency);
});
}catch (RestClientException ex) {
System.out.println(ex.getMessage());
}
Controller Class :
@GetMapping("/currency")
public List<Currency> findAll(){
return currencyService.getAllCurrencies();
}