java - 如何将具有动态变量名的 JSON 对象反序列化为 Java POJO?
问题描述
我正在尝试使用 RestTemplate 的getForObject
方法解析以下嵌套的 JSON 对象:
"rates":{
"USD":1.075489,
"AUD":1.818178,
"CAD":1.530576,
"PLN":4.536389,
"MXN":25.720674
}
货币汇率的数量取决于用户输入(可以是一个或多个)。
如何将此类对象列表或 HashMap 映射到 Java POJO 类?
我尝试在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
}
但是该rates
对象被反序列化为null
.
有人可以帮忙吗?提前非常感谢!
解决方案
感谢@Simon 和@bhspencer,我通过将JSON 对象导出到HashMap 解决了这个问题JsonNode
。
这是解决方案:
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>>() {});
推荐阅读
- python - 在python中分隔列CSV
- insert - Laravel 5.7 CRUD 解释
- database - 是否有可能使 mongoose 中的 MongoDB 成为像 Firebase 这样的实时数据库?
- r - 解释 glm 系数与 bootstrap 拟合系数的平均值
- reactjs - 如何在按钮单击时更新 GraphQL 查询
- flutter - 如何使用 OneSignal Flutter SDK 清除 OneSignal 通知?
- apache - 永久重定向不起作用
- python - 如何创建一个新的 typing.Dict[str,str] 并向其中添加项目
- python - RuntimeWarning:在日志中除以零,乘以无效值
- python - 如何永远运行异步 websocket 客户端?