3

What is the simplest way to define a custom mapping of a JSON property to a particular object property in RetroFit?

Example JSON response for a set of "rewards":

[
  {
    "name" : "$5 Voucher",
    "description" : "Get $5 off your next purchase",
    "assets" : {
      "icon" : "icon.png"
    }
  }
]

Reward class in my Android project:

public class Reward {
  @SerializedName("name")
  private String name;

  @SerializedName("description")
  private String description;

  @SerializedName("icon")
  private String icon;
}

Because name and description map 1:1 with the server response, RetroFit has no issues performing the mapping, but "icon" is null because I have no way of mapping the custom path of assets.icon to icon.

In the RestKit library for iOS, a fundamental feature is defining custom object mapping, which allows you to easily define these mappings with some key/value pairs. Does anything similar exist in RetroFit? Every solution I see seems to involve a lot of extra code for making custom converters. Is there no easier way?

Ted Avery
  • 5,639
  • 3
  • 30
  • 29

1 Answers1

2

try this:

class Reward {
    String name;
    String description;
    Asset assets;

    class Asset {
        String icon;
    }
}
zerodin
  • 857
  • 5
  • 9