Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moshi: problem with platform class BigDecimal

I have a class:

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

where Asset is a custom class I have. I'm trying to use Moshi but I'm getting the following error:

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

How can I work around this? I tried with

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

but it is crashing.

Thanks a lot in advance!

like image 807
noloman Avatar asked Mar 02 '19 11:03

noloman


Video Answer


1 Answers

As the exception says, this is a platform type, and you need to use its public API to encode and decode it.

object BigDecimalAdapter {
  @FromJson fun fromJson(string: String) = BigDecimal(string)

  @ToJson fun toJson(value: BigDecimal) = value.toString()
}

return Moshi.Builder()
    .add(BigDecimalAdapter)
    .add(KotlinJsonAdapterFactory())
    .build()
like image 149
Eric Cochran Avatar answered Oct 06 '22 09:10

Eric Cochran