Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple custom mapping of JSON property to object property with Retrofit

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?

like image 435
Ted Avery Avatar asked Jan 20 '26 07:01

Ted Avery


1 Answers

try this:

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

    class Asset {
        String icon;
    }
}
like image 74
zerodin Avatar answered Jan 22 '26 19:01

zerodin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!