LoginSignup
8
1

More than 5 years have passed since last update.

moshiでPOJO→JSON変換をする際にnullをシリアライズしたいときもあるよね📛

Last updated at Posted at 2018-02-07

nullをnullのままJSONに含みたい!

data class Hoge(val foo: Int? = null,
                val bar: String = "baz") : Serializable

こういうのを

{
  "foo": null,
  "bar": "baz"
}

こうしたい。

しかし、moshiでは、デフォルトの状態だとnullはシリアライズされずフィールドごと無かったことになります。

{
  "bar": "baz"
}

↑こうなる

ライブラリみっけた

moshi-lazy-adapters

このライブラリでは、様々なmoshiのアダプターを提供しています。gsonで見たことあるような機能が提供されてます。

導入

compile 'com.serjltt.moshi:moshi-lazy-adapters:2.1'

使用例

今回のようにnullをシリアライズしたい場合は以下のように使います。

data class Hoge(@Serializable val foo: Int? = null,
                val bar: String = "baz") : Serializable
val moshi = Moshi.Builder()
        .add(SerializeNulls.ADAPTER_FACTORY)
        .build()
val hoge = Hoge() 
val jsonAdapter = moshi.adapter(Hoge::class.java)
val json = jsonAdapter.toJson(hoge)

{
  "foo": null,
  "bar": "baz"
}

こうなります。

8
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
8
1