【发布时间】:2020-04-03 08:44:54
【问题描述】:
我是 Spring Boot 和 API 的新手,我正在开发一个项目,我需要从公共 API 获取数据并将其存储到本地数据库,尽管我的 Spring Boot 应用程序与 MySql 数据库连接。从 API 获取数据时,我的编译器抛出异常:
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]
我的总体思路是从公共 API 获取数据,将其存储在本地数据库中,然后根据我的项目要求使用这些数据。
我已经尝试了几乎所有来自 google 和 StackOverflow 的解决方案,但我没有任何想法。
我正在尝试获取的 JSON 格式:
[
{
"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
}
]
}
]
这里,我的 CurrencyDTO 类:
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
我调用 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());
}
控制器类:
@GetMapping("/currency")
public List<Currency> findAll(){
return currencyService.getAllCurrencies();
}
【问题讨论】:
标签: java json api spring-boot jackson