使用Retrofit处理变量JSON

时间:2016-03-29 08:46:25

标签: android json gson retrofit

我从后端获取数据(使用Retrofit),其中一个键包含一个JSON对象作为其值。我为这个对象编写了以下类结构:

public class NotificationData {
    @SerializedName("photo_pk")
    @Expose
    private int photoPk;
    @SerializedName("gallery_pk")
    @Expose
    private int galleryPk;
    @SerializedName("user_pk")
    @Expose
    private int userPk;
}

问题是此对象的值可以是null,如果不是null,则可以包含字段photo_pkgallery_pk或可能是gallery_pkuser_pk。如果后端发送所有字段并为现有字段提供值,而为其他字段提供null,那么它将完美地工作。但是由于某些字段即将到来而某些字段不存在,根据具体情况,我希望来自后端的值能够正确匹配,对于那些不是来自后端的字段,我希望它们是{{1}或其他一些默认值。我怎样才能做到这一点?

以下是示例JSON

null

我所指的字段是数据。它包含变量JSON。

2 个答案:

答案 0 :(得分:4)

使用Integer代替int。在这种情况下,您的变量可以为null。

public class NotificationData {
    @SerializedName("photo_pk")
    @Expose
    private Integer photoPk;
    @SerializedName("gallery_pk")
    @Expose
    private Integer galleryPk;
    @SerializedName("user_pk")
    @Expose
    private Integer userPk;
}

答案 1 :(得分:1)

根据复杂程度,有多种解决方案。

  1. 将int更改为Integer

  2. 尝试解析转换器中的JSON: https://stackoverflow.com/a/28576252/2429753