Search code examples
javaspring-bootserializationjacksondeserialization

Jackson deserialization fails after serializing an object using writeValueAsString


Using the com.fasterxml.jackson.databind.ObjectMapper class(com.fasterxml.jackson.core:jackson-databind:2.9.5) I am trying to deserialize an object of the following class:

class MyClass {

    String name;

    MyClass(String name) {
        this.name = name;
    }
}

The code I am currently executing is the following:

    MyClass myClass = new MyClass("test");
    objectMapper.registerModule(new ParameterNamesModule())
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule())
        .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
        .setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    String text = objectMapper.writeValueAsString(myClass);
    objectMapper.readValue(text, MyClass.class);

which fails on the last line throwing the exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.pckge.MyClass (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (String)"{"name":"test"}"; line: 1, column: 2]

My goal would be to configure the object mapper so to successfully deserialize the object without using annotations such as JsonCreator or JsonProperties on the constructor of MyClass:

  • Is this doable?
  • Which configuration I am missing?

Thanks a lot!

EDIT 1: Reply by @Dean solves the issue. However I would like to avoid to have the default constructor also.


Solution

  • Jackson uses Getter and Setters to set values. So you need to modify your class:

    class MyClass {
    
        String name;
    
        MyClass(String name) {
          this.name = name;
       }
    
       MyClass(){}
    
       public void setName(String name) {
         this.name = name;
       }
    
      public String getName(String name) {
         return this.name;
      }
    }