2021年3月23日火曜日

Kotlin Serialization は sealed class も対応していて便利

Kotlin Serialization

plugins { ... id "org.jetbrains.kotlin.plugin.serialization" version "1.4.31" } dependencies { ... implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0" } @Serializable data class Dog(val name: String, val age: Int, val sex: Sex, val kind: Kind) enum class Sex { MALE, FEMALE } @Serializable sealed class Kind { @Serializable object Hybrid : Kind() @Serializable data class PureBlood(val name: String) : Kind() } class DogTest { @Test fun list() { val dogs = listOf( Dog("White", 10, Sex.MALE, Kind.Hybrid), Dog("Black", 20, Sex.FEMALE, Kind.PureBlood("Husky")) ) val json = Json.encodeToString(dogs) println(json) // [{"name":"White","age":10,"sex":"MALE","kind":{"type":"net.yanzm.serialize.Kind.Hybrid"}},{"name":"Black","age":20,"sex":"FEMALE","kind":{"type":"net.yanzm.serialize.Kind.PureBlood","name":"Husky"}}] val decoded = Json.decodeFromString<List<Dog>>(json) assertThat(decoded).isEqualTo(dogs) } }

0 件のコメント:

コメントを投稿