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:
Thanks a lot!
EDIT 1: Reply by @Dean solves the issue. However I would like to avoid to have the default constructor also.
Overview. Jackson is a simple java based library to serialize java objects to JSON and vice versa.
Note that Jackson does not use java.
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.
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.
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;
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With