LoginSignup
18
17

More than 5 years have passed since last update.

Kotlin JSON (Moshi) 使い方

Last updated at Posted at 2018-04-20

KotlinでJSONを扱うのに Moshi を利用した。

ライブラリの設定

GradleにMoshiを追加する。

app/build.gradle
// 追加
implementation 'com.squareup.moshi:moshi:1.5.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.5.0'

jarで利用する場合は、以下を用意する。

libs
moshi-1.5.0.jar
okio-1.14.0.jar  ← moshiが利用している

エンティティ

User.kt

import com.squareup.moshi.Json

data class User(
        var name: String,
        var age: Int,
        @field:Json(name = "last_update")   // @Json(name = "last_update")
        var lastUpdate: Long                // ↑これだと、変換されなかった
)

JSON -> エンティティ に変換

val jsonText = ...
val adapter = Moshi.Builder().build().adapter(User::class.java)
val user = adapter.fromJson(jsonText)

エンティティ -> JSON に変換

val user = User("hoge", 1, System.currentTimeMillis())
val adapter = Moshi.Builder().build().adapter(User::class.java)
val jsonText = adapter.toJson(user)
18
17
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
18
17