0
2

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】Gsonでenumを使う

Posted at

以下のようにFruit enumを持つ、PersonというデータクラスをGsonでjson文字列に変換する例を考えます。


enum class Fruit(val value: String) {
    appleKey("appleValue"),
    bananaKey("bananaValue");
}

data class Person(val name: String, val favoriteFruit: Fruit) {
}

単純に変換すると次のようになります。


val jsonString = Gson().toJson(person);
Log.d(TAG, "${jsonString}")
// 出力
// {"favoriteFruit":"appleKey","name":"Jack"}

favoriteFruitに appleKey とenumのキーの値が文字列で入ってきています。
これで良ければ良いのですが、enumの値の方(appleValue)に変換してjsonを出力したいことが多いです。

以下のようにSerializerを登録することで実現できます。


val jsonString = GsonBuilder()
        .registerTypeAdapter(Fruit::class.java, object : JsonSerializer<Fruit> {
            override fun serialize(src: Fruit?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
                src?.let {
                    return JsonPrimitive(it.value)
                }
                return JsonNull.INSTANCE
            }
        })
        .create()
        .toJson(person)
Log.d(TAG, "${jsonString}")
//出力
//{"favoriteFruit":"appleValue","name":"Jack"}

enumの値 appleValue を使ってjson文字列を作成することができました。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?