I am working on a JSON parser for an Android application. When I call the server for data, there are some optional fields, how can I handle this in Retrofit using the GSON converter?
Normal answer
{ "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" } }
An alternative answer when there is no data in some fields
{ "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 to create POJO classes to handle optional fields that are not present? At the moment, the entire MyClassInformation object becomes NULL, when fields are lost, please help.
source share