1

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!

4
  • 1
    What about rates being a Map<String, BigDecimal > Commented Mar 20, 2020 at 16:05
  • I tried it, Rates still arrives as null - I added the following variable in Rates: private Map<String, BigDecimal> rates; Commented Mar 20, 2020 at 16:17
  • 1
    Your JSON structure suggests fields called 'USD', 'AUD' etc. You won't be able to deserialize that into a POJO. How about returning a Map<String, Serializable> from the RestTemplate? (that's possibly what @bhspencer meant) Commented Mar 20, 2020 at 16:23
  • Thanks a lot for pushing me in the right direction guys. Commented Mar 20, 2020 at 17:22

1 Answer 1

1

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>>() {});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.