5

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.

Tom Sabel
  • 3,935
  • 33
  • 45
Amit Tiwari
  • 3,684
  • 6
  • 33
  • 75

2 Answers2

4

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;
}
Ilya Tretyakov
  • 6,848
  • 3
  • 28
  • 45
1

Depending on the complexity there are multiple sollutions.

  1. Change int to Integer

  2. Try to parse the JSON in a converter: https://stackoverflow.com/a/28576252/2429753

Community
  • 1
  • 1
Tom Sabel
  • 3,935
  • 33
  • 45