How to handle additional 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 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.

+5
source share
2 answers

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

This is what I changed, From

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

For

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

Hope this helps anyone looking for a similar answer.

+2
source

I struggled with this a couple of years ago.

There is probably no good answer for this. At least I don’t know.

Three options are considered:

  • Set all members as required fields (provided that they are all known in advance) and set them to Null if the value is not received when the type makes sense (for example, it does not always make sense for primitive types). Here you are working more on those who pass you JSON, but your Java code is simpler but less flexible.
  • Specify optional fields inside the container for key-value pairs, where bothe key and value are Strings. The container may be empty if additional properties have not been passed. Here you have more flexibility, but you have to work harder to create serializers (de).
  • Use a combination of 1 and 2.

Each option has pros and cons, and I ended up with option 3.

Hope this helps and good luck!

0
source

Source: https://habr.com/ru/post/1233219/


All Articles