0
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 1 year has passed since last update.

kotlin serializationでMapをdecodeする

Posted at

Jsonをデコードする記事はたくさん有りましたが、今回はMapdata classに変換する方法を紹介します。

Mapを変換するために基本の依存関係の他に以下の依存関係が必要です。

implementation "org.jetbrains.kotlinx:kotlinx-serialization-properties:バージョン"

Mapから以下のようなモデルに変換する例を考えます。

@Serializable
data class Employee(val id:Int, val name: String) {}

デコードするためのコードはこんな感じ。

val map:Map<String,Any> = mapOf(
    "id" to 1,
    "name" to "sekitaka_1214"
)
val employee = Properties.decodeFromMap<Employee>(map)
Log.d("Employee",employee.toString())

以下のようにMapが意図したEmployeeクラスのインスタンスにデコードされています。

Employee(id=1, name=sekitaka_1214)
0
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
0
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?