Retrofit2:如何在具有不同字段名称的对象中接收JSON响应?

时间:2017-11-25 05:22:07

标签: android json web-services retrofit2

我的Android应用程序(从Web服务发送)的JSON响应低于:

{
    "result_code": 0,
    "status": "",
    "count": 2,
    "start_date": "2016-07-17T00:00:00",
    "end_date": "2018-07-18T23:59:00",
    "pagination_start": 1,
    "pagination_end": 10
}

我想知道如何以低于格式的对象存储此响应?我关注的是字段名称的差异。

public class Response {
    int result_code;
    String status;
    int count;
    Date startDate,endDate;
}

1 个答案:

答案 0 :(得分:2)

您可以使用GSON序列化库

来实现此目的

添加此依赖项

compile 'com.google.code.gson:gson:2.8.2'

您可以使用序列化注释

为您添加这样的POJO
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Response {

@SerializedName("result_code")
@Expose
private Integer resultCode;

@SerializedName("status")
@Expose
private String status;

@SerializedName("count")
@Expose
private Integer count;

@SerializedName("start_date")
@Expose
private String startDate;

@SerializedName("end_date")
@Expose
private String endDate;

@SerializedName("pagination_start")
@Expose
private Integer paginationStart;

@SerializedName("pagination_end")
@Expose
private Integer paginationEnd;
}

它会根据注释中的给定名称对您进行对象的序列化,而不是为该字段提供任何变量名称