square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.69k stars 758 forks source link

toJson exception in runtime #1736

Open SwimLi opened 1 year ago

SwimLi commented 1 year ago
@Keep
open class QualitieItemJsonData(

    @Json(name = "quality")
    val quality: String = "SUPER",

    @Json(name = "fps")
    val fps: Int = 24,

    @Json(name = "maxVideoBitrate")
    val maxVideoBitrate: Int? = null,

    @Json(name = "minVideoBitrate")
    val minVideoBitrate: Int? = null,

    @Json(name = "gop")
    val gop: Int? = null,
)

@Keep
class StatisConfig : QualitieItemJsonData {

    constructor():super()

    @Json(name = "h265Encode")
    var h265Encode: Boolean = false

    @Json(name = "h265Decode")
    var h265Decode: Boolean = false
}

private val moshi: Moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
val sta = StatisConfig()
moshi.adapter(StatisConfig::class.java).toJson(sta)

i get error: java.lang.IllegalArgumentException: Cannot serialize Kotlin type com.learn.testkt.moshi.StatisConfig. Reflective serialization of Kotlin classes without using kotlin-reflect has undefined and unexpected behavior. Please use KotlinJsonAdapterFactory from the moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.

but i modify like this,everything is well!??why?

@Keep
class StatisConfig : QualitieItemJsonData() {

    @Json(name = "h265Encode")
    var h265Encode: Boolean = false

    @Json(name = "h265Decode")
    var h265Decode: Boolean = false
}

kotlin version 1.7.10 implementation "com.squareup.moshi:moshi-kotlin:1.14.0"

NightlyNexus commented 4 months ago

The KotlinJsonAdapterFactory requires the primary constructor, so the constructor():super() is breaking it. The error message should be better, though.