首页 > 解决方案 > 如何将具有动态变量名的 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.

有人可以帮忙吗?提前非常感谢!

标签: javajsonspringrestresttemplate

解决方案


感谢@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>>() {});

推荐阅读