5
3

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

Gsonはデフォルトではnullなフィールドをシリアライズしない

Posted at

調べたのでメモ。
題名の通り、GsonはオブジェクトをJSONに変換する際、デフォルトではnullのフィールドをシリアライズしない。
nullのフィールドをシリアライズしたい場合、 GsonBuilder#serializeNulls() を使用する。

サンプルコード

MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val data = Data("nonnull", "nullable", null)

        val gson1 = Gson()
        val json1 = gson1.toJson(data)
        Log.d(TAG, json1)
        // => {"nonNullProp":"nonnull","nullableProp1":"nullable"}

        val gson2 = GsonBuilder().serializeNulls().create()
        val json2 = gson2.toJson(data)
        Log.d(TAG, json2)
        // => {"nonNullProp":"nonnull","nullableProp1":"nullable","nullableProp2":null}
    }

    data class Data(
        val nonNullProp: String,
        val nullableProp1: String?,
        val nullableProp2: String?
    )

    companion object {
        private const val TAG = "MainActivity"
    }
}

参考URL

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?