Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit - Can I map response data fields?

I'm testing/creating a REST client to the new Basecamp API using Retrofit. It looks something like this:

class Project {
  String name;
  String appUrl;
}

interface Basecamp {
    @GET("/projects.json")
    List<Project> projects();
}

In the json response, the source field for appUrl is called app_url. Asides from renaming the field in the class, is there a simple way to map the response data with my data structure?

like image 618
Mitkins Avatar asked Dec 06 '22 22:12

Mitkins


2 Answers

So I found the answer in this question. Turns out this can be solved using Gson:

class Project {
  String name;

  @SerializedName("app_url")
  String appUrl;
}
like image 91
Mitkins Avatar answered Dec 27 '22 03:12

Mitkins


If you are using Jackson for JSON parsing with Retrofit you can use the @JsonProperty annotation:

Example:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties (ignoreUnknown = true)
    class Project {
      @JsonProperty("name")
      String name;
      @JsonProperty("app_url")
      String appUrl;
    }
like image 31
Patrick Dorn Avatar answered Dec 27 '22 03:12

Patrick Dorn