Reputation: 1031
I am using Restlet to call an API that returns a JSON Array of objects. When making a similar call to pull back a single object, everything gets mapped correctly to the custom class, but when I pull back the array the Object is getting mapped as a LinkedHashMap instead of this custom object. I'm sure I just need to define how to deserialize the array correctly, but I haven't figured out exactly how to do that.
@Get("json")
public Trait getTrait();
@Get("json")
public HashSet<Trait> getTraits();
The former works fine, but the latter isn't work. Ultimately when I try to iterate through the HashSet I can this error: java.util.LinkedHashMap cannot be cast to com.test.traits.Trait.
Any help would be appreciated.
Upvotes: 0
Views: 1127
Reputation: 116522
This is generally because type is passed as class (like HashSet
) instead of generic type (HashSet<Trait>
). If so, this equivalent to HashSet<Object>
, and Jackson has no choice but to bind contents to simplest Object type available that matches which is just java.util.Collection
of some kind.
It sounds like Restlet is not passing generic type information correctly for some reason.
There are work-arounds to this:
List
s and Map
s are always properties of a Java object, never root-level values. This ensures that types work, even if Restlet did not pass generic type for root valueHashSet
so that you have non-generic type; Jackson can then figure out generic types for HashSet
For second case, you just do something like:
public class MyTraits extends HashSet<Trait> { }
and
@Get("json")
public MyTraits getTraits();
And it will work because MyTraits
has no generic type of its own; but its super-type declaration has generic parameters that are available to Jackson.
Upvotes: 2