JSON Serialization Interview Questions
DATA › Networking
What JSON libraries are common on Android, and how do they differ?
What a strong answer covers: Gson uses reflection, is old and isn't Kotlin-aware (it can put null into non-null fields and ignores default values). Moshi supports Kotlin with code generation or reflection and fails clearly on nulls. kotlinx.serialization uses a compiler plugin, no reflection, is multiplatform and respects nullability and defaults. New Kotlin projects typically use kotlinx.serialization or Moshi.
Why can Gson break Kotlin null safety?
What a strong answer covers: Gson creates objects with Unsafe, bypassing the constructor, and sets fields by reflection. If a JSON field is missing or null, a non-null Kotlin property ends up holding null with no error until you access it and get an NPE far away. Default parameter values also aren't applied. Kotlin-aware libraries respect the constructor, so they either use the default or fail at parse time.
How do you handle optional, missing or unknown fields with kotlinx.serialization?
What a strong answer covers: Give properties default values so missing fields use them; make fields nullable if null is a valid value; set ignoreUnknownKeys = true on the Json instance so new server fields don't break old clients; coerceInputValues to treat invalid values as defaults; and @SerialName to map JSON names to Kotlin names. explicitNulls controls how nulls are written.
How would you parse a polymorphic JSON response, like a feed with different item types?
What a strong answer covers: With kotlinx.serialization, model it as a sealed class with @Serializable subclasses and @SerialName values, using a 'type' class discriminator; for unknown types, provide a default deserializer that maps to an Unknown item so new server types don't crash old clients. Moshi has PolymorphicJsonAdapterFactory with a fallback. A custom JsonContentPolymorphicSerializer can decide by content when there's no discriminator.
How do you evolve an API's JSON schema without breaking older app versions that are still installed?
What a strong answer covers: Old versions stay in use for years, so changes must be additive: add fields as optional, never rename or remove fields or change types in place, give clients defaults and ignoreUnknownKeys, and handle unknown enum values and types with fallbacks. Version the API for breaking changes, use feature flags, add contract tests, and monitor parse failures in crash reporting by app version.