【问题标题】:Moshi fail to deserialize 0, 1 to "Boolean?"Moshi 无法将 0、1 反序列化为“布尔值?”
【发布时间】:2021-12-22 20:46:55
【问题描述】:

我们尝试将 JSON 字段从 0、1、null 反序列化为“布尔值?” 我们有这个自定义注解:

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class BooleanType

class BooleanAdapter {
    @FromJson
    @BooleanType
    fun fromJson(value: Int): Boolean {
        return value == 1
    }

    @ToJson
    fun toJson(@BooleanType value: Boolean): Int {
        return if (value) 1 else 0
    }
}

如果字段为 0 或 1,一切正常。但是当涉及到“null”时, 它总是抛出异常

No JsonAdapter for class java.lang.Boolean annotated [@com.pk.data.serialize.BooleanType()]
....

这是虚拟数据和单元测试

@JsonClass(generateAdapter = true)
data class HaHaData(
    @BooleanType
    @Json(name = "haha") val haha: Boolean?,
)


 @Test
    fun parseNullBooleanTest() {
        val moshi = Moshi.Builder()
            .add(BooleanAdapter())
            .build()
        val json = "{\"haha\":1}"
        val jsonWithNull = "{\"haha\":null}"
        val data = HaHaDataJsonAdapter(moshi).fromJson(json)
        val dataWithNull = HaHaDataJsonAdapter(moshi).fromJson(jsonWithNull) // exception thrown
        assert(data?.haha== true)
        assert(dataWithNull?.haha == null)
    }

【问题讨论】:

  • 如果给定值为空,布尔值应该是什么?它应该是 null 还是 false?

标签: java android json kotlin moshi


【解决方案1】:

您的fromJson 不接受null 作为输入。

如果你想让null 变为假:

fun fromJson(value: Int?): Boolean {
      return 
}

如果您希望 null 保留 null(您还必须修改 toJson 乐趣以接受空值):

fun fromJson(value: Int?): Boolean? {
    return value?.let { it == 1 }
}

【讨论】:

  • 但是如果我使用 fun fromJson(value: Int?): Boolean? { 返回值?.let { 它 == 1 } }。它仅适用于 val haha​​:Boolean?,不适用于 val haha​​:Boolean。我想要一个适配器来处理这些情况。有可能吗?
  • 布尔值?只是布尔+可能为空。布尔值?不排除布尔值。
猜你喜欢
  • 2010-09-10
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多