Skip to content
Advertisement

Gson: indexed object to list

I have a json object from an external API that has a “list” of objects in the form of:

JavaScript

My Deserializer and POJOs looks something like this:

JavaScript

Since all the keys of the pointData object are just indices I thought I could just deserialize this as a list rather than a map. When running this, Gson successfully gets through deserialization, but when I try to access the point data, I get a:

JavaScript

I’m not sure what’s going wrong here. I’ve read a bit about type erasure, which is something I’ve heard come up a lot when searching this problem, but I don’t really understand it very well.

Advertisement

Answer

It’s pretty easy in Gson.

JavaScript

The type adapter factory above does the following things:

  • checks if the target type is List (it does not really work with linked lists but it’s fine for simplification);
  • extracts the type parameter of the target list, hence its elements type and resolves a corresponding type adapter;
  • substitutes the original type adapter with a map-reading one that reads map keys assuming them as the new list indices (and enlarges the result list if necessary) and reads every map value using the original element type adapter. Note that the assumption that the list may have sparse indices is vulnerable and I only put it for demo purposes (say, the input JSON declares a single-element map with the only index “999999” that enlarges the list dramatically), so you can ignore the index value using the add(element) method only.

Simply annotate the pointData field in the Canvas class with @JsonAdapter(MapToListTypeAdapterFactory.class) and it will work.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement