当请求主体是列表或对象时,如何使用 RestTemplate 反序列化 JSON?

How to deserialize JSON with RestTemplate when the request body is either a list or an object?

我正在尝试通过消耗 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 转换器的情况下解决这个问题? 如果我必须创建它,我该怎么做?

通过使用解决:

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