简体   繁体   English

如何将具有动态变量名称的 JSON 对象反序列化为 Java POJO?

[英]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.

相关问题 如何使用 Jackson 将此动态键 JSON 反序列化为 Java 自定义 Pojo - How to deserialize this dynamic keys JSON to Java custom Pojo using Jackson 动态 Json 转 Java Pojo - Dynamic Json To Java Pojo 将具有不固定字段的Json反序列化为Java中的POJO - Deserialize Json with inconstant field to POJO in Java 将JSON字符串反序列化为列表列表Java POJO - Deserialize a JSON String into list of lists Java POJO 当JSON使用日期作为属性名称时,如何使用GSON将JSON反序列化为Java Object? - How can I deserialize JSON to Java Object using GSON when the JSON using dates as property names? 使用Jaxb / Jersey将动态JSON对象映射到Java POJO - Mapping a dynamic JSON object into Java POJO with Jaxb / Jersey JSON 到 JAVA 带动态密钥的 POJO - JSON to JAVA POJO with dynamic key 如何使用Jackson(Java)在Object中反序列化JSON Object? - How to deserialize json Object in Object with jackson(Java)? 如何将 map JSON 到 Java POJO 与 JSON 中的动态字段? - How to map JSON to Java POJO with a dynamic field in JSON? 如何反序列化具有转义 JSON 和动态密钥的参数字符串的自定义 object 和动态密钥到 Java Z439545559015BAC141 - How to deserialize a custom object that has a parameter string with escaped JSON and dynamic key into Java Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM