Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling variable JSON with Retrofit

I am getting data from backend (using Retrofit), one of whose key contains a JSON object as its value. I have written the following class structure for this object:

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

The problem is that the value of this object can be null or, if it isn't null, it can contain either the field photo_pk or gallery_pk or may be gallery_pk and user_pk. If the backend would have been sending all the fields and providing values for fields which exist and null for others, it would have worked perfectly. But since some fields are coming and some are not, depending on the situation, I want the values that are coming from backend to be matched properly and for those fields, which are not coming from backend, I want them to be null or some other default value. How can I achieve that?

Here is the sample 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
}

The field that I am referring is data. It contains variable JSON.

like image 334
Amit Tiwari Avatar asked Mar 29 '16 08:03

Amit Tiwari


Video Answer


1 Answers

Use Integer instead of int. In this case your variable could be 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;
}
like image 68
Ilya Tretyakov Avatar answered Sep 29 '22 06:09

Ilya Tretyakov