learner learner - 2 months ago 12
JSON Question

Jackson-jr read polymorphic ArrayList

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

[
{"test-1":["a","b","c","d"]},
{"test-2":["b","j","d"]},
{"test-3":["n","e","o","p","i"]},
{"test-4":["s","a","v","z","b","รง","x","p"]},
{"test-5":["d","q","u"]},
{"test-6":["f","b"]}
]


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:

arrays.get(i);


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

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);