2

I have an API for which one of its endpoints returns this json object (Comes from this API)

The problem about this is, it is not an array! It is a single simple object. But if you click the link and also think "wth is this documentation supposed to be": "BASE" actually respresents a currency like "USD". So in the end we have a map of Currency:Information pairs.

How can I parse this into an java object using Gson? Where there is an unkown number of "BASE":"INFO" mappings? (The keys are essentially unknown)

 {
  "BASE": {
    "commoditymarketvalue": 0,
    "futuremarketvalue": 0,
    "settledcash": 0,
    "exchangerate": 0,
    "sessionid": 0,
    "cashbalance": 0,
    "corporatebondsmarketvalue": 0,
    "warrantsmarketvalue": 0,
    "netliquidationvalue": 0,
    "interest": 0,
    "unrealizedpnl": 0,
    "stockmarketvalue": 0,
    "moneyfunds": 0,
    "currency": "string",
    "realizedpnl": 0,
    "funds": 0,
    "acctcode": "string",
    "issueroptionsmarketvalue": 0,
    "key": "string",
    "timestamp": 0,
    "severity": 0
  }
}
Avinta
  • 678
  • 1
  • 9
  • 26

1 Answers1

3

Do you want to deserialize it to the Map of String to some pojo? Like here: How to de-serialize a Map<String, Object> with GSON ?

(Edited after review) Solution from url:

static class PersonData {
    int age;
    String surname;
    public String toString() {
      return "[age = " + age + ", surname = " + surname + "]";
    }
  }

  public static void main(String[] args) {
    String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
    System.out.println(json);
    Gson gson = new Gson();
    Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
    System.out.println(decoded);
  }

If you want to be more flexible you can just deserialize it to Map.class and traverse through it as you like.

ByerN
  • 123
  • 7
  • Yes! As always I knew there was a solution but I did not had the correct keywords to google:) – Avinta Apr 21 '21 at 19:39