14

So I'm working with retrofit with an API that has a variable called "public". How would I go about getting it to automatically map like all the other variables do.

Example:

@GET("/?filter=my_images")
void getMyImages(
        @Query("client_id") String id,
        @Query("api_key") String key,
        Callback<ImageList> callback
);
public static class Image{
    int id;
    String name;
    String distribution;
    String slug;
    // Can't do this:
    boolean public;
}

public static class ImageList{
    String status;
    List<Image> images;
}

Example API results (json):

{
  "status": "OK",
  "images": [
    {
      "id": 1,
      "name": "My first snapshot",
      "distribution": "Ubuntu",
      "slug": "ubuntu-12.10-x32",
      "public": true
    },
    {
      "id": 2,
      "name": "Automated Backup",
      "distribution": "Ubuntu"
    }
  ]
}
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
JaySee
  • 351
  • 3
  • 14

2 Answers2

45

Retrofit uses Gson for serialization to and from JSON.

Gson provides a @SerializedName annotation in order to change the key to which a field or method is mapped. You can use this for handling your reserved word:

@SerializedName("public")
public String isPublic;
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • 1
    Worked like a charm. I'm new to dealing with annotations, so I forget to check out things like that. That'll also help to get rid of those ugly nonstandard variables with underscores. – JaySee Jun 21 '14 at 18:25
  • @JaySee you might also have a look at `setFieldNamingPolicy`/`setFieldNamingStrategy` options when creating your `GsonConverter` - these can be used to automatically map underscored JSON to camel-cased properties names (and vice-versa) – swanson Jun 25 '14 at 13:50
  • Hi Jake, can somebody from Square give some hints on this question please: http://stackoverflow.com/questions/24467416/retrofit-cache-control-never-included-in-response ? – Amio.io Jun 30 '14 at 06:55
0

Please look at this link, which is a neater solution if there are underscores in each key.

Community
  • 1
  • 1
user2195058
  • 887
  • 7
  • 10