【问题标题】:How to deserialize JSON with RestTemplate when the request body is either a list or an object?当请求正文是列表或对象时,如何使用 RestTemplate 反序列化 JSON?
【发布时间】:2020-02-13 17:43:41
【问题描述】:

我正在尝试通过使用 API 反序列化 JSON。 然而,来自 API 的 JSON 正文并不一致。有时它以列表的形式出现,有时以单个项目的形式出现。

例子:

"Charge": [
            {
              "ChargeType": "EXPRESS 12:00",
              "ChargeAmount": 0.0
            },
            {
              "ChargeCode": "YK",
              "ChargeType": "12:00 PREMIUM",
              "ChargeAmount": 0.0
            },
          ]

在另一种情况下:

"Charge": {
            "ChargeType": "EXPRESS",
            "ChargeAmount": 8.5
          }

我正在使用 RestTemplate 和 DTO。

我的 DTO 是这样构建的。

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Charges {

    @JsonProperty(value = "Currency")
    private String currency;

    @JsonProperty(value = "Charge")
    private List<Charge> charges;
}

当它作为一个对象出现时,这会失败:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<Charge>` out of START_OBJECT token

有没有办法在不创建自定义 JSON 转换器的情况下解决这个问题? 如果我必须创建它,我该怎么做?

【问题讨论】:

    标签: json deserialization resttemplate


    【解决方案1】:

    通过使用解决:

     @JsonProperty(value = "Charge")
     @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
     private List<Charge> charges;
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多