Skip to content
Advertisement

DynamoDB JsonMarshaller cannot Deserialize List of Object

I have a Java class which is the data-model of a table in DynamoDB. I want to use the DynamoDBMapper to save and load items from Dynamo. One member of the class is a List<MyObject>. So I used the JsonMarshaller<List<MyObject>> to serialize and de-serialize this field.

The list can be successfully serialized by the JsonMarshaller. However, when I try to retrieve the entry back and read the list, it throws an exception: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyObject. It looks like that the JsonMarshaller de-serialize the data into the LinkedHashMap instead of MyObject. How can I get rid of this problem?

The MCVE:

JavaScript

JavaScript

JavaScript

JavaScript

Advertisement

Answer

Part of the problem here is how the whole DynamoDB Mapper SDK deals with generics. The interface DynamoDBMarshaller<T extends Object> has a method T unmarshall(Class<T> clazz, String obj), in which the class to deserialize to is passed as a parameter. The problem is that there is type erasure, and the SDK doesn’t provide an easy to deal with this. Jackson is smarter in some cases (the JsonMarshaller uses Jackson), which explains why the serialize method works correctly.

You need to provide a better implementation for your deserialization. One way you could do this would be to implement the DynamoDBMarshaller interface rather than extending the other one (my opinion) so you have better control over how the type is serialized.

Here is an example that is essentially copy/paste of the JsonMarshaller, with minor tweaks in deserialization for the List to give you an idea:

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