改造-在序列化过程中动态添加字段 [英] Retrofit - add field dynamically during serialization

查看:122
本文介绍了改造-在序列化过程中动态添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在我的Android项目中使用Retrofit 2.3,并且最近我们使用的API已更新,因此它在所有POST请求中的JSON主体中都必须具有"version":number.假设我们需要传递UserCredentials对象-之前的请求主体只是使用GSON转换器序列化了,看起来像这样

I'm currently using Retrofit 2.3 in my Android project and recently the API we are using was updated so that it needs to have "version":number in JSON body in all POST requests. So let's say we need to pass UserCredentials object - previously body of the request was simply serialized using GSON converter and looked like this

{"username":"myUsername", "password":"myPassword"}

现在它必须具有其他版本"字段:

and now it has to have additional "version" field:

{"username":"myUsername", "password":"myPassword", "version":1}

我已经搜索了几个小时,如何设置自定义转换器工厂以进行改装,但是我发现的全部是如何从序列化中排除某些字段.我知道我可以简单地将"version"字段添加到我的所有POJO中,但是我发现这种方法肮脏",因为它将仅在向服务器发送数据期间使用.

I've googled couple of hours how to set custom converter factory to retrofit but all I found was how to exclude certain fields from serialization. I know I could simply add "version" field to all my POJOs but I found this approach 'dirty' as it's going to be used only during sending data to server.

以前有人做过这样的事吗?

Has anyone did something like this previously?

推荐答案

我做到了,但并非完全按照您想要的方式进行,您可以创建BaseRequest POJO类,在其中可以使用版本号并将该类扩展到您所使用的其他POJO类正在这样使用:

I did it but not exactly the way you want, you can create BaseRequest POJO class in which you can use version number and extend that class to other POJO classes you are using like this :

class BaseRequest{
@SerializedName("version")
public int version= 0;
 }

将此基本POJO类扩展到其他POJO类以使用这样的版本号:

Extend this base POJO class is to other POJO classes to use the version number like this :

class UserRequest extends BaseRequest{
  @SerializedName("username")
  public String userName = "";
  @SerializedName("password")
  public String password = "";
}

这种方法有很多好处,例如,如果您在API中需要一个字段,那么就不需要更改所有api.您只需在baserequest中添加一个字段即可实现这一目标.

There are lots of benefits of this approach like if you need one more field in your APIs then you don't need to change all of the apis. You can achieve that just by adding a field in your baserequest.

这篇关于改造-在序列化过程中动态添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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