java - JSON解析错误: Cannot deserialize instance of `` out of START_ARRAY token

标签 java json spring-boot jackson

我是 Spring Boot 和 API 的新手,我正在开发一个项目,尽管我的 Spring Boot 应用程序与 MySQL 数据库连接,但我需要从公共(public) API 获取数据并将其存储到本地数据库。从 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]

我的总体想法是从公共(public)API获取数据并将其存储在本地数据库中,然后根据我的项目需求使用这些数据。

我几乎尝试了 Google 和 Stack Overflow 上的所有解决方案,但我没有任何想法。

我尝试获取的 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

价格.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());
        }

Controller 类:

@GetMapping("/currency")
    public List<Currency> findAll(){
        return currencyService.getAllCurrencies();
    }

最佳答案

此外,您共享的json是CurrencyDTO的数组。假设你的 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更改为,

@Data
@NoArgsConstructor
public class CurrencyDTO {

    private String table;
    private String no;
    private String effectiveDate;

    private List<Rates> rates;
}

以及您的费率等级,

@Data
@NoArgsConstructor
public class Rates {

    private String currency;
    private String code;
    private Double mid;
}

它能够为我反序列化。 你做错的是 Dto 实例变量应该根据 Json 中的名称,或者你应该使用 @JsonProperty("nameInTheJson")

如果你想让它与你的 JSON 兼容,你可以使用 Array ofCurrencyDTO 您将能够反序列化,您可以将对象用作,

try {
       RestTemplate restTemplate = new RestTemplate();

       CurrencyDTO[] forObject =
                    restTemplate.getForEntity("http://api.nbp.pl/api/exchangerates/tables/a/", CurrencyDTO[].class).getBody();
          for (CurrencyDTO currencyDTO1 : forObject) {
                for (Rates rate : currencyDTO1.getRates()) {
                    Currency currency = new Currency(rate.getCode(), rate.getMid());
                    //you code to put the object inside the db
                    this.currencyRepository.save(currency);
                }
            }
        }catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

关于java - JSON解析错误: Cannot deserialize instance of `` out of START_ARRAY token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262566/

相关文章:

java - Spring with Google Spanner 引发错误

java - 如何知道用户何时完成输入?

javascript - 无法正确访问 json github api 响应

json - Scala 发送 GET 请求,无法解析 json 响应

spring-boot - Spring Boot 1和Gradle:ClassNotFoundException SpringApplicationBuilder

java - 使用 JoinTable(带有 OrderColumn)删除 OneToMany/ManyToOne 双向关系中的重复项

java - 客户端无法从另一个IP连接

javascript - 本地存储迭代获取for循环内单击按钮的值

java - 它没有捕获我的存储过程 Spring Boot 的错误

java - 当配置位置是 Windows 绝对路径时,Spring Boot 独立 jar 崩溃