Reputation:
I have a very simple Jackson code to deserialize a nested JSON object:
public class MapTest
{
public static void main(String ... args) throws Exception
{
final String ser = "{\"nested\":{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}}";
final Map<String, Object> deser = new ObjectMapper().readValue(ser, new TypeReference<TreeMap<String, Object>>(){});
System.out.println("Class of deser's nested object is " + deser.get("nested").getClass().getSimpleName());
}
}
When I run this I obtain the following output:
Class of deser's nested object is LinkedHashMap
However I want the nested map to be deserialized as a TreeMap
rather than as a LinkedHashMap
as per the output. How can I tell Jackson to default to use a TreeMap
when deserializing?
Reading through the documentation the closest thing I found was the ability to define concrete classes for abstract types through addAbstractTypeMapping()
in a module but I've tried every superclass and instance of LinkedHashMap
in an attempt to do this and nothing seems to work.
This is using Jackson 2.4.2, although if there is a way to do this that requires a higher version I would be able to upgrade.
Upvotes: 5
Views: 3090
Reputation: 116502
Module's addAbstractTypeMapping()
is indeed the way to achive mapping in general. But the problem may be due to recursive nature of deserialization; because inner values are considered to be of type java.lang.Object
.
However, I think there were indeed fixes to this part in 2.5, so I would specifically checking to see if 2.5.0 would work, once you add abstract mapping from Map
to TreeMap
.
If this does not work, please file a bug at https://github.com/FasterXML/jackson-databind/issues since it should work.
Upvotes: 2