1
0

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.

Retrofit データクラスで地味にハマったこと

Last updated at Posted at 2020-03-27

前提

APIは仮に以下のようにします。

{
  "items": [
     {
        "id": 100,
        "number": 10,
        "content": "sample",
        "created_at": "2020/03/26 21:30",
        "updated_at": "2020/03/26 21:30"
     }
  ],
  "delete_questions": [
    {"id": 10}
  ],
  "status": "ok"
}

今まで毎回同じフォーマットで帰ってくるAPIのレスポンスデータしか扱って来なかったので、データモデルといえば以下のように実装していました。

data class Item {
    val items: List<ItemInfo>,
    @Json(name = "delete_items")val deleteItems: List<DeleteItemInfo>,
    val status: Int
}

APIのフォーマットがレスポンスによって変わる場合

ところが実際にはAPIのレスポンスとしては以下のような場合もあるとします。

{
  "items": [
    {
      "id": 1,
      "number": 1,
      "content": "sample",
      "created_at": "2020/03/26 21:30",
      "updated_at": "2020/03/26 21:30"
    },
    {
      "id": 2,
      "number": 2,
      "content": "sample",
      "created_at": "2020/03/26 21:30",
      "updated_at": "2020/03/26 21:30"
    }
  ],
  "status": "ok"
}

このようにdelete_itemsはあったりなかったりするAPIレスポンスの場合、上記のデータモデルではdeleteItemsがnullになりエラーとなりアプリが落ちてしまいます。

その場合、データモデルを以下のように変更します。

data class Item {
    val items: List<ItemInfo>,
    // deleteItemsをnull許可にする
    @Json(name = "delete_items")val deleteItems: List<DeleteItemInfo>?,
    val status: Int
}

これでレスポンスにdelete_itemsが含まれていても、いなくても、問題ありません。

自分だけかもしれませんが、データクラスの型にnull許可にするというのがあまり意識したことがありませんでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?