4
0

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 5 years have passed since last update.

kotlinx.serializationメモ

Posted at

kotlinx.serializationの雑なメモ

Jsonの項目名を指定する

json
{
  "id": 1,
  "name": "aaa",
  "created_at": "Sun May 20 2018 20:33:49 GMT+0900 (JST)"
}
User.kt
@Serializable
data class User(
  val id: Long,
  val name: String,
  @SerialName("created_at")
  val createdAt: String
){}

配列の場合

  1. JSON.parseの第一引数にKSerializer<T>.listを指定する
json
[
  {
    "id": 1,
    "name": "aaa"
  },
  {
    "id": 2,
    "name": "bbb"
  }
]
User.kt
@Serializable
data class User(
  val id: Long,
  val name: String
){}
Parse.kt
fun parseList(json: String) = JSON.parse<List<User>>(User.serializer().list, json)

Jsonに含まれていない属性がある場合

  1. @Optionalアノテーションを付ける
  2. Nullableにする
  3. デフォルト引数にnullを指定する
json
[
  {
    "id": 1,
    "name": "aaa"
    "age": 20
  },
  {
    "id": 2,
    "name": "bbb"
  }
]
User.kt
@Serializable
data class User(
  val id: Long,
  val name: String,
  @Optional
  val age: Int? = null
){}
4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?