Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 433
pafede2 Avatar asked Jul 18 '18 13:07

pafede2


People also ask

Which methods does Jackson rely on to serialize a Java object *?

Overview. Jackson is a simple java based library to serialize java objects to JSON and vice versa.

Does Jackson use Java serialization?

Note that Jackson does not use java.

How does Jackson deserialize dates from JSON?

How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.

What is serialization and Deserialization in Jackson?

3. Serialization. Serialization converts a Java object into a stream of bytes, which can be persisted or shared as needed. Java Maps are collections that map a key Object to a value Object, and are often the least intuitive objects to serialize.


1 Answers

The proper way to solve this without a default constructor is to add JsonCreator and JsonProperty annotations to your class constructor.

class MyClass {

    String name;

    @JsonCreator
    MyClass(@JsonProperty("name") String name) {
        this.name = name;
    }
    ...
}
like image 155
steve Avatar answered Sep 19 '22 08:09

steve