Simple custom mapping of JSON property to object property with Retrofit

五迷三道 提交于 2019-12-23 18:15:00

问题


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?


回答1:


try this:

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

    class Asset {
        String icon;
    }
}


来源:https://stackoverflow.com/questions/24007149/simple-custom-mapping-of-json-property-to-object-property-with-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!