I'm trying to use Jackson as a generic serialization engine instead of Java serialization. By initializing the mapper in the following way:
objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
All type information in stored in JSON so I'm able to write and read all my objects back with:
objectMapper.readValue(json, Object.class)
I'm having problems when I try to serialize and then deserialize java arrays. Since Jackson doesn't store the array type into the JSON it fails later in the deserialization phase. In the following code:
String [] strings = {"A", "B", "C"};
try {
String json = objectMapper.writeValueAsString(strings);
String [] stringsBack = (String [])objectMapper.readValue(json, Object.class);
if (!strings.equals(stringsBack)) {
System.err.println("ERROR, stringsBack not the same!!!\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
json will be set to "["A","B","C"]" but on deserialization I get the following exception:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid type id 'A' (for id type 'Id.class'): no such class found
at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:66)
at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:48)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:157)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:94)
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromAny(AsArrayTypeDeserializer.java:68)
at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:494)
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3560)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2576)
at Main.run(Main.java:86)
Is there a way to instruct Jackson to store java arrays types information as well into JSON? My serialization engine is generic and doesn't know in advance the type it is going to read from the JSON string.
objectMapper.readValue(json, String[].class);? You told Jackson to deserialize an Object, and of course it has no idea what type of object it is.