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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With