【发布时间】: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