【问题标题】:Retrofit2: How to receive JSON response in object with different field names?Retrofit2:如何在具有不同字段名称的对象中接收 JSON 响应?
【发布时间】:2018-05-09 00:51:21
【问题描述】:

我的 android 应用程序有以下 JSON 响应(从 Web 服务发送):

{
    "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;
}

【问题讨论】:

    标签: android json web-services retrofit2


    【解决方案1】:

    您可以通过使用 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;
    }
    

    它将根据注释中的给定名称对您的对象进行序列化,然后您可以为该字段提供任何变量名称

    【讨论】:

    • 是否需要@Expose
    • 不...因为我已经从 jsonschema 生成代码
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多