learner learner - 11 months ago 47
JSON Question

Jackson-jr read polymorphic ArrayList

I'm using Jackson-jr to read my JSON files. One of them is a bit complex:


My code to read is very simple:

InputStream inputStream = assetManager.open("test.json");
ArrayList<HashMap<String, ArrayList<String>>> arrays = JSON.std.beanFrom(ArrayList.class, inputStream);

My intention is to get each array to work with each of them:


But, when this line is executed I have an Exception:

Caused by: java.lang.ClassCastException: com.fasterxml.jackson.jr.ob.impl.DeferredMap cannot be cast to java.util.HashMap

Jackson-jr doesn't have TypeFactory, TypeReference or ObjectMapper. Some links that I found answers for jackson, not for jackson-jr:

ClassCastException when convert json to list of objects

Jackson custom deserializer for one field with polymorphic types

Tricky(?) JSON, polymorphic deserialization

Is there a say to handle this in Jackson-Jr?

Answer Source

You should program to the interface and not to implementation classes. As the returned Map implementation is DeferredMap and not HashMap, you get the ClassCastException. Change the assignment as below

List<Map<String, List<String>>> arrays = JSON.std.beanFrom(ArrayList.class, inputStream);