Deserializing JSON with Jackson - Why JsonMappingException "No suitable constructor"?

The error messages says it all, your ProtocolContainer does not have a default constructor so Jackson is unable to create an instance of it. (Since the only current way of creating a ProtocolContainer is by passing in a DataPacket.)


In this case, you could add @JsonCreator annotation to constructor. There are two ways it could be done:

  • If you only add that annotation, then the whole matching JSON is first bound to type of the only argument (`DataPacket'). I assume you do not want to do that.
  • If you also add @JsonProperty annotation before the argument, then JSON property matching that name is passed to constructor (annotation is mandatory because Java byte code does NOT contain name of method or constructor arguments) -- I suspect you want @JsonProperty("SubPacket")

This works if necessary information for constructor comes from JSON. If not, you do need to add alternate no-arg constructor.

By the way, the error message does sound wrong in this case. It should only be given if JSON data matching expected value if a JSON String.


Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!

Simply add a default constructor and it should work.

Tags:

Java

Json

Jackson