Android 通过改造处理变量JSON
我从后端(使用改型)获取数据,其中一个键包含一个JSON对象作为其值。我已经为此对象编写了以下类结构:Android 通过改造处理变量JSON,android,json,gson,retrofit,Android,Json,Gson,Retrofit,我从后端(使用改型)获取数据,其中一个键包含一个JSON对象作为其值。我已经为此对象编写了以下类结构: public class NotificationData { @SerializedName("photo_pk") @Expose private int photoPk; @SerializedName("gallery_pk") @Expose private int galleryPk; @SerializedName("use
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\u pk
或gallery\u pk
,也可以是gallery\u pk
和user\u pk
。如果后端发送所有字段并为存在的字段提供值,并为其他字段提供null
,那么它就可以完美地工作。但是,由于有些字段出现了,有些字段没有出现,根据具体情况,我希望来自后端的值能够正确匹配,对于那些不来自后端的字段,我希望它们是null
或其他一些默认值。我怎样才能做到这一点
下面是示例JSON
{
'display':{
'image':'https://kdfnvdfkdvd',
'title':'fkfjkfdvfldvmdflv',
'large_text':'bvfdkvkdfv',
'icon':'something.jpg',
'image_format':'SQUARE'
},
'data':{
'image_pk':9
},
'notif_id':8,
'screen':'IMAGE',
'priority':0,
'time':'2016-02-06 15:22:33',
is_read:False
}
我指的领域是数据。它包含变量JSON。使用
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;
}
根据复杂性,有多种解决方案
您能分享api之后得到的json示例吗call@ankitaggarwal我已经编辑了这个问题。看一看。尝试将此
gson
实例传递给改装Gson Gson=new GsonBuilder().serializeNulls().create()代码>谢谢,让我试试,如果有效,我会接受答案。