LoginSignup
7
2

More than 5 years have passed since last update.

同じ構造だけどプロパティ名の違うJSONを1つのモデルクラスにマッピングする

Posted at

昨日知りました!

APIが

{
  "name" : "山田太郎",
  "premium" : true
}
{
  "user_name" : "山田太郎",
  "premium_user" : true
}

こんな感じで、同じ構造だけどプロパティ名違うレスポンスを返してきて、困ったなーって思いましたが
Gsonがフィールドに対して、別名を定義する機能があったので、解決しました。

class User {

  @SerializedName(
    value = "name",
    alternate = "user_name"
  )
  public String name;

  @SerializedName(
    value = "premium",
    alternate = {"premium_user"}
  )
  public boolean premium;
}

参考

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