2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

  • kotlin: 1.4.10
  • kotlinx.serialization: 1.0.1

Jsonのパースをkotlinx.serializationの0.2.0で行っていましたが、Kotlinが1.4になったことにより、いろいろ変わったみたいなのでやり直し。

導入

build.gradle(app)の記述だけでよくなったようです。

build.gradle(app)
plugins {
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.10'
}

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1"
}

実装

テストコードで実行。ドキュメントのサンプルそのままです。

package jp.co.sankosc.jsonsample

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.junit.Test

@Serializable
data class Data(val a: Int, val b: String)

class ExampleUnitTest {

	@Test
	fun jsonTest() {
		val string = Json.encodeToString(Data(42, "str"))
		println(string)
		val obj = Json.decodeFromString<Data>(string)
		println(obj)

		val dataList = listOf(Data(42, "test1"), Data(12, "test2"))
		val jsonList = Json.encodeToString(dataList)
		println(jsonList)
		val objList = Json.decodeFromString<List<Data>>(jsonList)
		println(objList)
	}
}
実行結果
{"a":42,"b":"str"}
Data(a=42, b=str)
[{"a":42,"b":"test1"},{"a":12,"b":"test2"}]
[Data(a=42, b=test1), Data(a=12, b=test2)]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?