How do you handle null values during serialization with GSON?
A) By using GsonBuilder().serializeNulls()
B) By using the @Expose annotation
C) By overriding the equals() method
D) By setting a flag in the JSON
Answer:
A) By using GsonBuilder().serializeNulls()
Explanation:
In GSON, you can handle null values during serialization by using the GsonBuilder().serializeNulls()
method. This option tells GSON to include null values in the JSON output, rather than omitting them.
For example:
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(someObject);
In this example, the serializeNulls()
method ensures that fields with null values are included in the JSON output, with their values explicitly set to null
.