Search code examples
javajsongson

parsing JSON with a lot of similar fields


I have this kind of json response:

"rates": {
  "first":1,
  "second":2,
  "thirds":3,
...
}

i'm using Gson, so my response class looks like this:

Public class Rates{
@SerializedName("first")
    private Integer first;
@SerializedName("second")
    private Integer second;
@SerializedName("first")
    private Integer third;

...
}

The problem is that there are 100 of this fields and some of them may be null and how can i get those which are not null, without calling all getters. May be there is a way to store fields in hashMap inside Rates or e.t.c?


Solution

  • Especially if all these fields have the same type (Integer), the easiest solution would probably be to deserialize as Map<String, Integer> instead of your custom Rates class.

    For example:

    Gson gson = new Gson();
    TypeToken<Map<String, Integer>> mapType = new TypeToken<Map<String, Integer>>() {};
    
    Map<String, Integer> rates = gson.fromJson(json, mapType);
    System.out.println(rates.get("first"));
    

    (When using Gson < 2.10 you have to call mapType.getType())

    See also the user guide for more information.