JSON属性的简单的自定义映射对象属性与改造 [英] Simple custom mapping of JSON property to object property with Retrofit

查看:708
本文介绍了JSON属性的简单的自定义映射对象属性与改造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是定义在改造特定对象属性JSON属性的自定义映射关系最简单的方法?

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

一组奖励的例子JSON响应:

Example JSON response for a set of "rewards":

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

在我的Andr​​oid项目奖励类:

Reward class in my Android project:

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

  @SerializedName("description")
  private String description;

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

由于名称和说明图1:1的服务器响应,改造具有执行映射没有问题,但偶像为null,因为我没有映射 assets.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.

RestKit 库的iOS,一个基本特点是定义的自定义对象映射,它可以让您轻松与一些键/值对定义这些映射。是否任何类似的改造存在吗?每一个解决方案,我看似乎涉及了很多额外的code制作定制的转换器。有没有更简单的方法?

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?

推荐答案

试试这个:

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

    class Asset {
        String icon;
    }
}

这篇关于JSON属性的简单的自定义映射对象属性与改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆