posted 9 years ago
I'm trying to create a utility method that calls Gson to deserialize a List of generic objects... Let's say they are "Widget" in a concrete example. Aka, the JSON is of the form: [{...},{...}] where {...} represents a serialized Widget object.
Below are two methods that both compile just fine. I've pulled out of a lot of extra businessy stuff, so apologize in advance if I pulled out so much it doesn't work!
The first method works as expected, and I get back a List of Widgets. Great if I am only working with Widgets, but as it turns out I need to support hundreds of different objects. Hence generics.
The second method appears to compile/run without issue, in fact I can even call toString() on the List and it prints the contents. The problem is that it is actually a List of LinkedTreeMap, not a List of Widgets. As soon as you call a Widget method like... result.get(0).getWidgetName(), it throws a ClassCastException.
While I understand this problem is related to type erasure, I'm wondering if anyone has a solution. I came across numerous posts using 'the Google' where people tried to get around this but had difficulty. I found one example where you can pass Widget[].class instead of Widget.class and then load the elements into an Array, but it feels hacky and I don't want the client to pass Widget[].class, I want them to pass Widget.class!
Any ideas?