I got here searching for this error:
No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator
Nothing to do with Retrofit but if you are using Jackson this error got solved by adding a default constructor to the class throwing the error. More here: https://www.baeldung.com/jackson-exception
You need to use jackson-module-kotlin
to deserialize to data classes. See here for details.
The error message above is what Jackson gives you if you try to deserialize some value into a data class when that module isn't enabled or, even if it is, when the ObjectMapper
it uses doesn't have the KotlinModule
registered. For example, take this code:
data class TestDataClass (val foo: String)
val jsonString = """{ "foo": "bar" }"""
val deserializedValue = ObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)
This will fail with the following error:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `test.SerializationTests$TestDataClass` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
If you change the code above and replace ObjectMapper
with jacksonObjectMapper
(which simply returns a normal ObjectMapper
with the KotlinModule
registered), it works. i.e.
val deserializedValue = jacksonObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)
I'm not sure about the Android side of things, but it looks like you'll need to get the system to use the jacksonObjectMapper
to do the deserialization.
If you're using Lombok on a POJO model, make sure you have these annotations:
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
It could vary, but make sure @Getter
and especially @NoArgsConstructor
.
I know this is an old post, but for anyone using Retrofit, this can be useful useful.
If you are using Retrofit + Jackson + Kotlin + Data classes, you need:
implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2'
to your dependencies, so that Jackson can de-serialize into Data classes val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()
val retrofit = Retrofit.Builder()
...
.addConverterFactory(JacksonConverterFactory.create(jsonMapper))
.build()
Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.
I solved this issue by adding a no argument constractor. If you are using Lombok, you only need to add @NoArgsConstructor
annotation:
@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
@EqualsAndHashCode
public class User {
private Long userId;
private String shortName;
}
As the error mentioned the class does not have a default constructor.
Adding @NoArgsConstructor to the entity class should fix it.
I had a similar issue (using Jackson, lombok, gradle) and a POJO without no args constructor - the solution was to add
lombok.anyConstructor.addConstructorProperties=true
to the lombok.config file
Extending Yoni Gibbs's answer, if you are in an android project using retrofit and configure serialization with Jackson you can do these things in order to deserialization works as expected with kotlin's data class.
In your build gradle import:
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"
Then, your implementation of retrofit:
val serverURL = "http://localhost:8080/api/v1"
val objectMapper = ObjectMapper()
objectMapper.registerModule(KotlinModule())
//Only if you are using Java 8's Time API too, require jackson-datatype-jsr310
objectMapper.registerModule(JavaTimeModule())
Retrofit.Builder()
.baseUrl(serverURL)
.client(
OkHttpClient.Builder()
.readTimeout(1, TimeUnit.MINUTES)//No mandatory
.connectTimeout(1, TimeUnit.MINUTES)//No mandatory
.addInterceptor(UnauthorizedHandler())//No mandatory
.build())
.addConverterFactory(
JacksonConverterFactory.create(objectMapper)
)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
Data class:
@JsonIgnoreProperties(ignoreUnknown = true)
data class Task(val id: Int,
val name: String,
@JsonSerialize(using = LocalDateTimeSerializer::class)
@JsonDeserialize(using = LocalDateTimeDeserializer::class)
val specificDate: LocalDateTime?,
var completed: Boolean,
val archived: Boolean,
val taskListId: UUID?
I had this issue and i fixed with the code below.
@Configuration
open class JacksonMapper {
@Bean
open fun mapper(): ObjectMapper {
val mapper = ObjectMapper()
...
mapper.registerModule(KotlinModule())
return mapper
}
}
I'm using rescu with Kotlin and resolved it by using @ConstructorProperties
data class MyResponse @ConstructorProperties("message", "count") constructor(
val message: String,
val count: Int
)
Jackson uses @ConstructorProperties. This should fix Lombok @Data as well.
If you are using LOMBOK. Create a file lombok.config if you don't have one and add this line.
lombok.anyconstructor.addconstructorproperties=true
My cause of issue seems very uncommon to me, not sure if anybody else gets the error under same condition, I found the cause by diffing previous commits, here you go :
Via my build.gradle I was using these 2 compiler options, and commenting out this line fixed the issue
//compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']
If you are using Unirest as the http library, using the GsonObjectMapper
instead of the JacksonObjectMapper
will also work.
<!-- https://mvnrepository.com/artifact/com.konghq/unirest-object-mappers-gson -->
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-object-mappers-gson</artifactId>
<version>2.3.17</version>
</dependency>
Unirest.config().objectMapper = GsonObjectMapper()
When you are using Lombok builder you will get the above error.
@JsonDeserialize(builder = StationResponse.StationResponseBuilder.class)
public class StationResponse{
//define required properties
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
public static class StationResponseBuilder {}
Reference : https://projectlombok.org/features/Builder With Jackson
I could resolve this problem in Kotlin with help of @JacksonProperty
annotation. Usage example for above case would be:
import com.fasterxml.jackson.annotation.JsonProperty
...
data class Station(
@JacksonProperty("repsol_id") val repsol_id: String,
@JacksonProperty("name") val name: String,
...
Encountered the same error in below Usecase.
I tried to hit the Rest(Put mapping) end point using sprint boot(2.0.0 Snapshot Version) without having default constructor in respective bean.
But with latest Spring Boot versions(2.4.1 Version) the same piece of code is working without error.
so the bean default constructor is no longer needed in latest version of Spring Boot
Just want to point out that this answer provides a better explanation.
Basically you can either have @Getter
and @NoArgConstructor
together
or let Lombok regenerates @ConstructorProperties
using lombok.config
file,
or compile your java project with -parameters
flags,
or let Jackson use Lombok's @Builder
Source: Stackoverflow.com