The following code attempts to serialize a data class containing a nullable field. What's the potential issue, and how would you fix it to handle the nullable field appropriately?

Android interview question for Advanced practice.

Answer

The code might produce unexpected JSON if age and/or email are null. The solution is to use the @Optional annotation on the nullable fields to control how nulls are handled in the JSON output.

Explanation

The potential issue is that, depending on the default Json configuration, null values might be represented inconsistently or omitted from the JSON output. For better control and predictability, annotating the nullable fields with @Optional is recommended. This allows you to explicitly specify how null values should be handled (e.g., omitted, represented as null, or represented as an empty string). Example: kotlin @Serializable data class User(val name: String, @Optional val age: Int?, @Optional val email: String?)

Related Questions