No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

AndroidKotlinJacksonRetrofit2

Android Problem Overview


I am trying to consume an API using Retrofit and Jackson to deserialize. I am getting the onFailure error No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator.

Android Solutions


Solution 1 - Android

Reason: This error occurs because jackson library doesn't know how to create your model which doesn't have an empty constructor and the model contains constructor with parameters which didn't annotated its parameters with @JsonProperty("field_name"). By default java compiler creates empty constructor if you didn't add constructor to your class.

Solution: Add an empty constructor to your model or annotate constructor parameters with @JsonProperty("field_name")

If you use a Kotlin data class then also can annotate with @JsonProperty("field_name") or register jackson module kotlin to ObjectMapper.

You can create your models using http://www.jsonschema2pojo.org/.

Solution 2 - Android

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

Solution 3 - Android

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.

Solution 4 - Android

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.

Solution 5 - Android

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:

  1. add 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
  2. When building retrofit, pass the Kotlin Jackson Mapper, so that Retrofit uses the correct mapper, ex:
    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.

Solution 6 - Android

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

Solution 7 - Android

I am using Quarkus, Jackson and Lombok. So I solved this issue by adding @Jacksonized attribute on model class. So all attributes are:

@Jacksonized //missing
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ...

Solution 8 - Android

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;
}

Solution 9 - Android

As the error mentioned the class does not have a default constructor.

Adding @NoArgsConstructor to the entity class should fix it.

Solution 10 - Android

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.

Solution 11 - Android

Just need to add @NoArgsConstructor and it works.

Solution 12 - Android

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?

Solution 13 - Android

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
    }
}

Solution 14 - Android

Bek's answer is correct.

But in-case someone is trying to use immutable class in restcontroller i.e they are using lombok's @value then you need to add lombok.anyConstructor.addConstructorProperties=true

You can create a file named lombok.config in the same location where the root pom.xml is present and add this line into the file

https://stackoverflow.com/a/56022839/6700081

Solution 15 - Android

Be carefull with Lombok, expecially with @Builder.

what fixed the issue for me was :

   @JsonDeserialize(builder = X.XBuilder.class)
       class X{
          @JsonPOJOBuilder(withPrefix = "")
          public static class XBuilder{

          }
}

I hope it will make your life easier

Solution 16 - Android

If you are using LOMBOK. Create a file lombok.config if you don't have one and add this line.

lombok.anyconstructor.addconstructorproperties=true

Solution 17 - Android

Add Constructor in class OR if you are using pojo add @NoArgsConstructor @AllArgsConstructor

Also include JsonProperty - @JsonProperty("name") private List<Employee> name;

Solution 18 - Android

I got the same error and after I added a constructor without parameters and then the problem was solved.

enter image description here

Solution 19 - Android

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()

Solution 20 - Android

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

Solution 21 - Android

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,
...

Solution 22 - Android

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

Solution 23 - Android

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']

Solution 24 - Android

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

Solution 25 - Android

I got the same error and the problem was that my model didn't implement Serializable, so check this as well, might help since this is also one of the reason.

Solution 26 - Android

I also faced the exception in Kotlin. If you're still having problem after applying KotlinModule, you might (though not quite probably) have value class somewhere.

Solution 27 - Android

I'm adding my answer, because I myself, due to my inattention, encountered this error.

Accidentally introduced the wrong serializer through the import of a static object and for a long time could not understand what was the reason. Maybe this will help someone else.

// Wrong serializer via static object import
import static org.keycloak.util.JsonSerialization.mapper;

Be careful.

Solution 28 - Android

For cases where we don't have a default construct for example when working with immutable obejects, Jackson by default will not be able to deserialize JSON to the object. We can resolve this using some annotations like @JsonCreator which can help Jackson to know how to deserialize a given JSON.

A sample code will look like:

package com.test.hello;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Payment {

    private final Card card;

    private final Amount amount;

    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public Payment(@JsonProperty("card") Card card, @JsonProperty("amount") Amount amount) {
       this.card = card;
       this.amount = amount;
    }

    public Card getCard() {
       return card;
    }

    public Amount getAmount() {
        return amount;
    }
}

Solution 29 - Android

by adding @NoArgsConstructor , it will fix the issue. Because compiler will add the default constructor if we have not provided any constructor, but if we have added any parameterized constructor and missed to add NoArgsConstructor we will get this exception. We should compulsorily add the default Constructor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJos&#233; NobreView Question on Stackoverflow
Solution 1 - AndroidBekView Answer on Stackoverflow
Solution 2 - AndroidFede MikaView Answer on Stackoverflow
Solution 3 - AndroidYoni GibbsView Answer on Stackoverflow
Solution 4 - Androidsilver_foxView Answer on Stackoverflow
Solution 5 - AndroidHATView Answer on Stackoverflow
Solution 6 - AndroidDominik MincView Answer on Stackoverflow
Solution 7 - AndroidMichalPrView Answer on Stackoverflow
Solution 8 - AndroidOusamaView Answer on Stackoverflow
Solution 9 - AndroidGayan WeerakuttiView Answer on Stackoverflow
Solution 10 - AndroidAaron LeeView Answer on Stackoverflow
Solution 11 - AndroidsadhnaView Answer on Stackoverflow
Solution 12 - Androidpeterzinho16View Answer on Stackoverflow
Solution 13 - AndroidElias MeirelesView Answer on Stackoverflow
Solution 14 - AndroidfirstpostcommenterView Answer on Stackoverflow
Solution 15 - AndroidSalvatore Pannozzo CapodiferroView Answer on Stackoverflow
Solution 16 - AndroidManjunath JoshiView Answer on Stackoverflow
Solution 17 - AndroidCodingBeeView Answer on Stackoverflow
Solution 18 - AndroidNguyễn DươngView Answer on Stackoverflow
Solution 19 - AndroidClementView Answer on Stackoverflow
Solution 20 - AndroidMohanaRao SVView Answer on Stackoverflow
Solution 21 - AndroidmiradhamView Answer on Stackoverflow
Solution 22 - AndroidCharles ChenView Answer on Stackoverflow
Solution 23 - AndroidMadis MänniView Answer on Stackoverflow
Solution 24 - AndroidKmsView Answer on Stackoverflow
Solution 25 - AndroidHarsh GundechaView Answer on Stackoverflow
Solution 26 - AndroidSKOView Answer on Stackoverflow
Solution 27 - AndroidAlexey BrilView Answer on Stackoverflow
Solution 28 - AndroidKaran KhannaView Answer on Stackoverflow
Solution 29 - AndroidshruthiView Answer on Stackoverflow