Gson & Deserialization of Objects Containing Arrays

After my practicum team and I banged our collective heads against the wall for several hours trying to force Gson to deserialize json arrays into a collection of complex classes containing their own collections, we chose to go another route entirely. Our problem at the time was that we had blinders on and couldn’t walk away from using Javas Collections library. I came to realize today that Gson does a fantastic job of deseralizing classes with any depth of arrays so long as those json arrays are actually represented as primitive arrays in your java class.

For example: let’s say you had the following json:

[
  {
    "name":"Beagle",
    "colors":["black","white","tan"]
  },
  {
    "name":"Dalmation",
    "colors":["white","black"]
  }
]

My previous attempts to deserialize this object might have been to create the following class:

class Dog {
  String name;
  ArrayList colors;
}

And deserialize using the following code (per the user guide):

Gson gson = new Gson();
Type collectionType = new TypeToken>(){}.getType();
ArrayList dogs = gson.fromJson(input, collectionType);

We tried a good deal of tricks to get this to work but never had any real luck with it. Today, while trying it again for a different project I read one section up in the user guide and it hit me… why not use primitive arrays? They seem to be more straightforward and (for my current needs) I won’t benefit from any of what Collections provide. So a quick change in code:

class Dog {
  String name;
  String[] colors;
}

Deserialization with:

Gson gson = new Gson();
Dog[] dogs = gson.fromJson(input, Dog[].class);

This is so much simpler. If I ever absolutely need to use Collections in a class that is built from JSON there are options (such as using a primitive-based class to construct the final class), but this solves about 90% of problems I’ve needed to apply Gson to thus far.