LoginSignup
6

More than 5 years have passed since last update.

KotlinでMoshiを使って、Json → List<Class>, List<Class> -> Jsonを行うExtension

Last updated at Posted at 2018-11-08

ToDo あとで説明書く予定(まずコードのみ)
変換したJsonはPreferencesに保存を想定

StringExtension.kt
/**
 * JsonのStringを特定クラスのListに変換する
 */
inline fun <reified T> String.jsonToList(): List<T>? {
    val moshi = Moshi.Builder().build()
    val listMyData = Types.newParameterizedType(List::class.java, T::class.java)
    val jsonAdapter: JsonAdapter<List<T>> = moshi.adapter(listMyData)

    try {
        return jsonAdapter.fromJson(this)
    } catch (e: Exception) {
        LogUtils.d("ERROR:", "JsonParseError : ${e.message}")
    }
    return null
}

/**
 * JsonのStringを特定クラスに変換する
 */
inline fun <reified T> String.jsonToObject() : T? {
    val moshi = Moshi.Builder().build()
    val jsonAdapter: JsonAdapter<T> = moshi.adapter(T::class.java)

    try {
        return jsonAdapter.fromJson(this)
    } catch (e: Exception) {
        LogUtils.d("ERROR:", "JsonParseError : ${e.message}")
    }
    return null
}

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
6