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

[Kotlin]JSON文字列をMapに変換する

Last updated at Posted at 2021-04-28

巨大なJSONを扱う必要があり、変換用のクラスを作るのが面倒でMapにしたかった時のメモ

JacksonのObjectMapperとTypeReferenceを使います

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper

val json = 巨大なJSON

// Json -> Map変換
val mapper = ObjectMapper()
val jsonMap: Map<String?, Any?>? = mapper.readValue<Map<String?, Any?>>(json, object : TypeReference<Map<String?, Any?>?>() {})

// Mapから値を取り出す
jsonMap?.get("取り出したいキー")

上記はJSONがこんな形の場合の例

{
  id: 123
  user: "hoge"
}

jsonが配列に入ってる場合は

[
  {
    id: 123
    user: "hoge"
  }
  {
    id: 456
    user: "fuga"
  }
]

こんな感じにします

val jsonMap: List<Map<String?, Any?>?> = mapper.readValue<List<Map<String?, Any?>>>(json, object : TypeReference<List<Map<String?, Any?>?>>() {})
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?