JSON Serialization Flashcards
DATA › Networking
- How does kotlinx.serialization generate serializers, and how is that different from Gson?
- A Kotlin compiler plugin generates a KSerializer for each @Serializable class at compile time, so there is no runtime reflection. Gson builds adapters reflectively at runtime, which is slower and blind to Kotlin types.
- What two things are required to use kotlinx.serialization in a Gradle module?
- Apply the org.jetbrains.kotlin.plugin.serialization Gradle plugin and add the runtime dependency (e.g. kotlinx-serialization-json). The plugin generates the serializers; the runtime provides Json and the format.
- By default, does kotlinx.serialization fail on unknown JSON keys, and how do you change it?
- Yes, by default unknown keys throw SerializationException. Configure a Json instance with ignoreUnknownKeys = true to skip them, which is standard for evolving server APIs.
- In kotlinx.serialization, what happens to a missing field, and when is a default applied?
- If a property has a default value, a missing JSON key uses that default; if it has no default and is non-nullable, decoding throws MissingFieldException. Defaults are not written out unless encodeDefaults = true.
- Compare Moshi's two Kotlin strategies: codegen versus the reflection adapter.
- Codegen uses @JsonClass(generateAdapter = true) with KSP to generate adapters at compile time, with no kotlin-reflect dependency. KotlinJsonAdapterFactory works reflectively at runtime but pulls in the ~2.5 MiB kotlin-reflect. Codegen is preferred for size and speed.
- How does Moshi handle Kotlin default values and absent fields for a data class?
- Moshi understands the primary constructor: an absent JSON key falls back to the property's Kotlin default, and a non-null property with no default and no value throws JsonDataException. This respects Kotlin nullability, unlike Gson.
- How do you serialize a sealed class hierarchy polymorphically in kotlinx.serialization?
- Annotate the sealed parent and subclasses with @Serializable; the plugin emits a class discriminator (default key 'type') so the right subtype is chosen. Use @SerialName to set stable type names and SerializersModule for open/non-sealed polymorphism.
- When and how do you write a custom serializer in kotlinx.serialization?
- Implement KSerializer<T> with descriptor, serialize, and deserialize for types you do not own or that need non-default encoding (e.g. dates). Attach it via @Serializable(with = MySerializer::class) or @file:UseSerializers.
- Why is kotlinx.serialization generally preferred over Gson for new Kotlin code?
- It is compile-time and reflection-free (smaller, faster, R8-friendly), Kotlin-first (honors nullability, defaults, sealed classes), multiplatform-capable, and actively maintained by JetBrains, whereas Gson is reflection-based, Kotlin-unaware, and effectively in maintenance mode.