Petar Bivolarski
Petar Bivolarski

Reputation: 1757

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:

  "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?

I tried with composition in the rates object:

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.

Could somebody please help? Thanks a lot in advance!

Upvotes: 1

Views: 911

Answers (1)

Petar Bivolarski
Petar Bivolarski

Reputation: 1757

Thanks to @Simon and @bhspencer I solved the issue by exporting the JSON object to a HashMap using JsonNode.

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

Upvotes: 1

Related Questions