我有一个 JSON 示例
{
"data":"some string data",
"amount":200,
"amountCurrencyList":[
{"value":4000.0,"currency":"USD"},
{"value":100.0,"currency":"GBP"}
]
}
以及当前将其解析为基础对象的映射字段的方法
public void buildDetailsFromJson(String details) {
if (details != null) {
TypeReference<HashMap<String, Object>> mapTypeReference = new TypeReference<HashMap<String, Object>>() {
};
ObjectMapper mapper = new ObjectMapper();
try {
mapper.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
detailsMap = mapper.readValue(details, mapTypeReference);
} catch (IOException e) {
log.error("Exception during JSON {} parsing! {}", details, e.getMessage());
}
}
}
JSON 结构可以更改。想法是有一个单独的方法,理想情况下可以轻松提取所需的参数,例如map.get(key_name)
例如
public void setUpFieldsFromMap() {
HashMap<String, Object> map = super.detailsMap;
this.amountCurrencyList = (ArrayList<MoneyValue>) map.get("amountCurrencyList");
if (isNull(amountCurrencyList)) {
throw new InvalidOrMissingParametersException("Exception during JSON parsing! Critical data is missing in DetailsMap - " + map.toString());
}
}
因此,通过按键获取 List 对象并将其转换为所需的参数。但是当我尝试操作时List<MoneyValue>
System.out.println(detailsObj.getAmountCurrencyList().get(0).getValue());
我越来越
Exception: java.util.LinkedHashMap cannot be cast to MoneyValue
实际上是否有可能实现我想要的,而无需使用精确的参数对 TypeReference 进行硬编码TypeReference<HashMap<String, List<MoneyValue>>>?
UPD
public class MoneyValue {
@NotNull
private BigDecimal value;
@NotNull
private String currency;
EventDetails 类
public class SomeEventDetails extends BaseEventDetails implements EventDetails {
private ArrayList<MoneyValue> amountCurrencyList;
泛舟湖上清波郎朗
相关分类