3

I want to know if there is some way to get the following deserializing properly:

public class MyClass {
     Map<String, Serializable> map;
     OtherObject object;
     [...]
}

ObjectMapper mapper = new ObjectMapper();
MyClass instance = mapper.readValue(someJson, MyClass);

Currently, I'm trying and I get an exception

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.io.Serializable: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
cjamesm
  • 109
  • 7
  • I think the error message is pretty clear... – rmlan Nov 13 '18 at 17:25
  • 1
    I understand that, I was hoping for a way to manipulate the ObjectMapper such that it can handle this sort of object. – cjamesm Nov 13 '18 at 17:28
  • `Serializable` is a polymorphic type. This requires some extra work in Jackson. See for example: https://stackoverflow.com/questions/30362446/deserialize-json-with-jackson-into-polymorphic-types-a-complete-example-is-giv – Robert Nov 13 '18 at 17:29

2 Answers2

1

As of v2.10.0, Jackson supports naive deserialization of 'Serializable' values, i.e., it will consider 'Serializable' the same as 'Object'. See this Github issue for more details.

So update Jackson to 2.10.0+ and try.

  • YMMV. I changed a field from `Object` to `Serializable`. My problem was about JSON serialization with regard to `ObjectMapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT)`. I wanted the type info for `Serializable` field to be included (just like `Object`), but updating to v2.10.0 does *not* change the behavior here. As other posts suggested, I ended up changing my field back to `Object` instead. – quietmint Feb 08 '22 at 22:25
0

You can change your data class's Map property declaration to not reference Serializable:

public class MyClass {
     Map<String, ?> map;
     OtherObject object;
     [...]
}

This will affect the signature of the Map's getter and setter as well. This does loosen type-checking, however, and the the map's values could be any subclass of Object instead of implementations of Serializable. If that's an important detail, you could do post-serialization validation of the map values.

Or you can configure a custom Deserializer, as those in your question's comments have suggested. It's just a matter of where you want to add the code, and that depends on how widespread this case is in your application.

RichW
  • 2,004
  • 2
  • 15
  • 24