Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle optional JSON fields in Retrofit for Android?

I am working on a JSON parser for an Android application. When I call the server for data, there are some optional fields, how do I handle this in Retrofit using GSON converter?

Normal response

{
   "status":"SUCCESS",
   "class-1":{
      "class.enddate":"Jan/10/2016",
      "class.startdate":"Jan/10/2015",
      "class.title":"Physics 1",
      "class.short.description":"Physics 1",
      "class.description":"This is a Physics Class"
   }
}

Alternate response, when some fields do not have any data

{
  "status":"SUCCESS",
  "class-1":{
     "class.enddate":"Jan/10/2016",
     "class.startdate":"Jan/10/2015",
     "class.title":"Physics 1"
   }
}

POJO Classes

public class MyClass {
    @Expose @SerializedName("status")
    public String status;

    @Expose @SerializedName("class-1")
    public MyClassInformation myClassInformation;
}

public class MyClassInformation {
    @Expose @SerializedName("class.title")
    public String classTitle;

    @Expose @SerializedName("class.short.description")
    public String classShortDescription;

    @Expose @SerializedName("class.description")
    public String classDescription;

    @Expose @SerializedName("class.startdate")
    public String startDate;

    @Expose @SerializedName("class.enddate")
    public String endDate;
}

How do I create the POJO classes in a way to handle the optional fields not being present? At the moment the whole MyClassInformation object becomes NULL when fields become missing, Please help.

like image 459
joeldroid Avatar asked Oct 08 '15 07:10

joeldroid


1 Answers

I managed to solve this by trial and error, managed to get it working by removing the @Expose annotation and changing the Gson constructor... Now the whole object does not get nulled or excluded if fields are missing and only the missing fields show up as null.

This is what I changed, From

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

To

Gson gson = new GsonBuilder().create();

Hope it helps anyone, who is looking for a similar answer.

like image 143
joeldroid Avatar answered Oct 22 '22 17:10

joeldroid