Home > database >  Ignore a property in moshi if the value is not present
Ignore a property in moshi if the value is not present

Time:10-11

I have the following property in my data class

@Parcelize
@JsonClass(generateAdapter = true)
data class CatalogProduct(
    @Json(name = "recommended")
    val recommended: Int = 0
) : Parcelable

I get the following error:

Expected an int but was BOOLEAN at path $.products[0].recommended at $.products[0].recommended

As the response I get back from the API may not contain that value as its optional.

The following will not show the error if the value is not present.

@Transient
@Json(name = "recommended")
val recommended: Int = 0

However, if the response contains that value then it will always be excluded

If I make the property nullable like this then the error will show again:

@Json(name = "recommended")
val recommended: Int? = 0

How can I have recommended so it will be ignored if there is no value present in the response and not ignored if there is a value?

I am using the following dependencies and version

moshiVersion = '1.11.0'

implementation "com.squareup.moshi:moshi:$moshiVersion"
implementation 'com.serjltt.moshi:moshi-lazy-adapters:2.2'
kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion"
implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion"

CodePudding user response:

Ignore a property in moshi if the value is not present

In general, I just use val propertyName: Type?, it works fine in my project.

@Json(name = "email") val email: String,
@Json(name = "userName") val userName: String?,
@Json(name = "isSignup") val isSignup: Boolean?,
...

Regards your description, why not use Boolean?, because I checked the error :

Expected an int but was BOOLEAN at path $.products[0].recommended at $.products[0].recommended

If I understand correctly, it means that the type doesn't match each other. The server return Boolean but you use Int in the data class.

How about this?

@Json(name = "recommended") val recommended: Boolean?
  • Related