[英]How to Deserialize JSON object with dynamic variable names to a Java POJO?
I am trying to parse the following nested JSON object using RestTemplate's getForObject
method:我正在尝试使用 RestTemplate 的
getForObject
方法解析以下嵌套的 JSON 对象:
"rates":{
"USD":1.075489,
"AUD":1.818178,
"CAD":1.530576,
"PLN":4.536389,
"MXN":25.720674
}
The number of currency rates varies depending on user input (it can be one or more).货币汇率的数量取决于用户输入(可以是一种或多种)。
How can I map such list of objects or a HashMap to a Java POJO class?如何将此类对象列表或 HashMap 映射到 Java POJO 类?
I tried with composition in the rates
object:我尝试在
rates
对象中组合:
public class Rates implements Serializable {
private List<ExternalApiQuoteCurrencyRate> list;
// getter and no-args constructor
}
public class ExternalApiQuoteCurrencyRate implements Serializable {
private String currency;
private BigDecimal rate;
// getters and no-args constructor
}
But the rates
object gets deserialized as null
.但是
rates
对象被反序列化为null
。
Could somebody please help?有人可以帮忙吗? Thanks a lot in advance!
非常感谢!
Thanks to @Simon and @bhspencer I solved the issue by exporting the JSON object to a HashMap using JsonNode
.感谢@Simon 和@bhspencer,我通过使用
JsonNode
将 JSON 对象导出到 HashMap 解决了这个问题。
Here is the solution:这是解决方案:
ResponseEntity<JsonNode> e = restTemplate.getForEntity(API_URL, JsonNode.class);
JsonNode map = e.getBody(); // this is a key-value list of all properties for this object
// but I wish to convert only the "rates" property into a HashMap, which I do below:
ObjectMapper mapper = new ObjectMapper();
Map<String, BigDecimal> exchangeRates = mapper.convertValue(map.get("rates"), new TypeReference<Map<String, BigDecimal>>() {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.