【问题标题】:Moshi: problem with platform class BigDecimalMoshi:平台类 BigDecimal 的问题
【发布时间】:2019-07-24 06:32:07
【问题描述】:

我有一堂课:

@JsonClass(generateAdapter = true)
data class DayAveragePriceModel(
    val asset: Asset,
    val value: BigDecimal
)

Asset 是我拥有的自定义类。我正在尝试使用Moshi,但出现以下错误:

Caused by: java.lang.IllegalArgumentException: Platform class java.math.BigDecimal (with no annotations) requires explicit JsonAdapter to be registered

我该如何解决这个问题?我试过了

        return Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .add(Object::class.java)
            .build()
    }

但它正在崩溃。

提前非常感谢!

【问题讨论】:

    标签: android json moshi


    【解决方案1】:

    正如例外所说,这是一个平台类型,您需要使用它的公共 API 对其进行编码和解码。

    object BigDecimalAdapter {
      @FromJson fun fromJson(string: String) = BigDecimal(string)
    
      @ToJson fun toJson(value: BigDecimal) = value.toString()
    }
    
    return Moshi.Builder()
        .add(BigDecimalAdapter)
        .add(KotlinJsonAdapterFactory())
        .build()
    

    【讨论】:

    • 我正在尝试按照您的示例为 ULong 和 UByte 添加适配器,但将它们各自的适配器添加到构建器后仍然出现错误。
    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2011-01-19
    相关资源
    最近更新 更多