I have an object like this:
class Test {
List<Integer> a;
}
I want both the following JSON to be parsed correctly:
{ "a" : "[1, 2, 3]" }
{ "a" : [1, 2, 3] }
When I try to deserialize it in Jackson with the data type as follows, it throws the following exception:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot deserialize value of type
java.util.ArrayList<java.lang.Integer>from String value (tokenJsonToken.VALUE_STRING)
How can I create a custom deserializer for this case? I've already tried creating one like the following, and it doesn't work and wasn't called during deserialization, probably because of generic type erasure.
val jackson = ObjectMapper().apply {
registerModule(SimpleModule().addDeserializer(ArrayList::class.java, object : JsonDeserializer<ArrayList<Integer>>() {
override fun deserialize(parser: JsonParser, context: DeserializationContext) =
parser.text.trim('[', ']').split(',').map { it.toInt() } as ArrayList<Integer>
}))
}
Well, I found a solution. If you are ready to use a
JsonNode, this is possible. Although this code does not involve yourTestclass, maybe you can work on it yourself. Try below mentioned code:You can comment/uncomment the
enteredJsonand check.EDIT
Here is another solution that involves your
Testclass.And your main class:
For this solution I have passed
Objectinto thesetmethod, you can figure out the rest.