I am trying to consume an API using retrofit and jackson to deserializitation. The error present in the title “No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator” appear in the onFailure.
This is the JSON I want to fetch:
{
"data": {
"repsol_id": "1129",
"name": "ES-MASSAMÁ",
"latitude": "38.763733333",
"longitude": "-9.258619444000001",
"address": "RUA GENERAL HUMBERTO DELGADO, LT.16",
"post_code": "2745-280",
"location": "QUELUZ",
"service_store": 1,
"service_mechanical_workshop": 0,
"service_restaurant": 0,
"service_wash": 1
}
}
This is my HomeFragment:
onCreate(){
viewModel.retrieveStation().observe(this, Observer {
dataBinding.favouriteStationTxt.text = it.name
})
}
This is my viewModel:
class HomeViewModel @Inject constructor(
private val stationRepository: StationRepository
) : ViewModel() {
private val station = MutableLiveData<Station>()
fun retrieveStation():LiveData<Station> = station
fun loadStations(stationId:Int){
stationRepository.getStationFromId(stationId,{ station.postValue(it)},{})
}
}
This is my repository:
class StationRepository @Inject constructor(var apiManager: ApiManager) {
fun getStationFromId(stationId:Int,onSuccess: (Station)->Unit, onError: (Exception)->Unit){
apiManager.getStation(stationId, onSuccess,onError)
}
}
This is my API Manager ( that joins several api managers)
class ApiManager @Inject constructor(
private val stationsApiManager: StationsApiManager,
){
fun getStation(stationId: Int, onSuccess: (Station)->Unit, onFailure: (e: Exception)->Unit){
stationsApiManager.getStation(stationId,{onSuccess(it.data.toDomain())},onFailure)
}
}
This is my StationAPiManager
class StationsApiManager @Inject constructor(private val stationApiService: StationsApiService){
fun getStation(stationId: Int, onSuccess: (StationResponse)->Unit, onFailure: (e: Exception)->Unit){
stationApiService.getStation(stationId).enqueue(request(onSuccess, onFailure))
}
private fun <T> request(onSuccess: (T)->Unit, onFailure: (e: Exception)->Unit)= object : Callback<T> {
override fun onFailure(call: Call<T>, t: Throwable) {
Log.d("error",t.message)
onFailure(Exception(t.message))
}
override fun onResponse(call: Call<T>, response: Response<T>) {
Log.d("Success",response.body().toString())
if(response.isSuccessful && response.body() != null) onSuccess(response.body()!!)
else
onFailure(Exception(response.message()))
}
}
}
This is my STationsApiService ( Base URL is in the flavors)
@GET("{station_id}")
fun getStation(@Path("station_id") stationId: Int): Call<StationResponse>
This is my StationResponse
class StationResponse (
@JsonProperty("data")
val data: Station)
This is my Station model
data class Station(
val repsol_id: String,
val name: String,
val latitude: String,
val longitude: String,
val address: String,
val post_code: String,
val location: String,
val service_store: Boolean,
val service_mechanical_workshop: Boolean,
val service_restaurant: Boolean,
val service_wash: Boolean
)
This is my DataMappers:
import com.repsol.repsolmove.network.movestationsapi.model.Station as apiStation
fun apiStation.toDomain() = Station(
repsol_id.toInt(),
name,
latitude.toDouble(),
longitude.toDouble(),
address,
post_code,
location,
service_store,
service_mechanical_workshop,
service_restaurant,
service_wash
)
Try below models. I used http://www.jsonschema2pojo.org/ to create these models.
StationResponse.java
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"data"
})
public class StationResponse {
@JsonProperty("data")
private Data data;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("data")
public Data getData() {
return data;
}
@JsonProperty("data")
public void setData(Data data) {
this.data = data;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Data.java
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"repsol_id",
"name",
"latitude",
"longitude",
"address",
"post_code",
"location",
"service_store",
"service_mechanical_workshop",
"service_restaurant",
"service_wash"
})
public class Data {
@JsonProperty("repsol_id")
private String repsolId;
@JsonProperty("name")
private String name;
@JsonProperty("latitude")
private String latitude;
@JsonProperty("longitude")
private String longitude;
@JsonProperty("address")
private String address;
@JsonProperty("post_code")
private String postCode;
@JsonProperty("location")
private String location;
@JsonProperty("service_store")
private Integer serviceStore;
@JsonProperty("service_mechanical_workshop")
private Integer serviceMechanicalWorkshop;
@JsonProperty("service_restaurant")
private Integer serviceRestaurant;
@JsonProperty("service_wash")
private Integer serviceWash;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("repsol_id")
public String getRepsolId() {
return repsolId;
}
@JsonProperty("repsol_id")
public void setRepsolId(String repsolId) {
this.repsolId = repsolId;
}
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("latitude")
public String getLatitude() {
return latitude;
}
@JsonProperty("latitude")
public void setLatitude(String latitude) {
this.latitude = latitude;
}
@JsonProperty("longitude")
public String getLongitude() {
return longitude;
}
@JsonProperty("longitude")
public void setLongitude(String longitude) {
this.longitude = longitude;
}
@JsonProperty("address")
public String getAddress() {
return address;
}
@JsonProperty("address")
public void setAddress(String address) {
this.address = address;
}
@JsonProperty("post_code")
public String getPostCode() {
return postCode;
}
@JsonProperty("post_code")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
@JsonProperty("location")
public String getLocation() {
return location;
}
@JsonProperty("location")
public void setLocation(String location) {
this.location = location;
}
@JsonProperty("service_store")
public Integer getServiceStore() {
return serviceStore;
}
@JsonProperty("service_store")
public void setServiceStore(Integer serviceStore) {
this.serviceStore = serviceStore;
}
@JsonProperty("service_mechanical_workshop")
public Integer getServiceMechanicalWorkshop() {
return serviceMechanicalWorkshop;
}
@JsonProperty("service_mechanical_workshop")
public void setServiceMechanicalWorkshop(Integer serviceMechanicalWorkshop) {
this.serviceMechanicalWorkshop = serviceMechanicalWorkshop;
}
@JsonProperty("service_restaurant")
public Integer getServiceRestaurant() {
return serviceRestaurant;
}
@JsonProperty("service_restaurant")
public void setServiceRestaurant(Integer serviceRestaurant) {
this.serviceRestaurant = serviceRestaurant;
}
@JsonProperty("service_wash")
public Integer getServiceWash() {
return serviceWash;
}
@JsonProperty("service_wash")
public void setServiceWash(Integer serviceWash) {
this.serviceWash = serviceWash;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Answer:
You need to use jackson-kotlin-module
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.
Answer:
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
Answer:
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
.
Answer:
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:
- 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 - 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.
Answer:
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
Answer:
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.
Answer:
As the error mentioned the class does not have a default constructor.
Adding @NoArgsConstructor to the entity class should fix it.
Answer:
I had the same symptoms the other day while using JsonCreator and JsonProperty but I got the same exact error message. In my case it turned out the json had a primitive type boolean
, whereas my constructor awaited the wrapper class Boolean
. So the framework was not able to find a suitable constructor.
Answer:
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()
Answer:
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
Answer:
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,
...
Tags: androidandroid, object, sed, struct