【问题标题】:Ignore a property in moshi if the value is not present如果值不存在,则忽略 moshi 中的属性
【发布时间】:2021-11-28 20:14:02
【问题描述】:

我的数据类中有以下属性

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

我收到以下错误:

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

由于我从 API 返回的响应可能不包含该值作为其可选值。

如果值不存在,以下将不会显示错误。

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

但是,如果响应包含该值,那么它将始终被排除在外

如果我像这样使属性为空,那么错误将再次显示:

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

如果响应中不存在值,我该如何推荐它会被忽略,如果有值则不会被忽略?

我正在使用以下依赖项和版本

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"

【问题讨论】:

    标签: android kotlin moshi


    【解决方案1】:

    如果值不存在,则忽略 moshi 中的属性

    一般来说,我只使用val propertyName: Type?,它在我的项目中运行良好。

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

    关于你的描述,为什么不使用Boolean?,因为我检查了错误:

    应为 int,但在路径 $.products[0].recommended 处为 BOOLEAN。在 $.products[0].recommended

    如果我理解正确,这意味着类型彼此不匹配。服务器返回Boolean,但您在数据类中使用Int

    这个怎么样?

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

    【讨论】:

      猜你喜欢
      • 2017-02-15
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2022-01-18
      • 2022-08-03
      • 1970-01-01
      相关资源
      最近更新 更多