When an Android app queries a web API, the server transmits payloads formatted as JSON (JavaScript Object Notation). To work with this data in Kotlin, the app must deserialize the raw JSON text into typed Kotlin data classes. In this class, we compare the three primary parsers: Kotlinx Serialization, Moshi, and legacy Gson.
| Dimension | Google Gson (Legacy) | Square Moshi (Modern) | Kotlinx Serialization (Recommended) |
|---|---|---|---|
| Null-Safety Handling | Dangerous! Uses Unsafe reflection; can assign null to non-nullable Kotlin properties without warning! | Respects Kotlin nullability rules via Kotlin reflect/code-gen | 100% Native Kotlin Type-Safe; validates nulls and defaults strictly |
| Performance & Code Gen | Pure runtime reflection (slow startup on Android) | Annotation processing (KSP) code generation (fast) | Compile-time Kotlin compiler plugin (zero reflection overhead!) |
| Platform Support | JVM / Android only | JVM / Android only | Multiplatform (KMP): Android, iOS, WebAssembly, Desktop |
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import kotlinx.serialization.json.Json
@Serializable
data class UserDTO(
@SerialName("user_id")
val id: Int,
@SerialName("full_name")
val name: String,
@SerialName("email_address")
val email: String,
@SerialName("is_vip")
val isVip: Boolean = false // Default fallback if missing in JSON!
)
fun parseJsonExample() {
val rawJson = """
{
"user_id": 404,
"full_name": "Jordan Smith",
"email_address": "jordan@veewom.com"
}
""".trimIndent()
val jsonConfig = Json {
ignoreUnknownKeys = true // Prevents crashes when backend adds new fields!
coerceInputValues = true // Coerces invalid nulls to default values
}
val user: UserDTO = jsonConfig.decodeFromString(rawJson)
Log.d("ParsedUser", "User name: ${user.name}, VIP: ${user.isVip}")
}
Google's Gson was built for Java. It bypasses Kotlin constructors entirely by using sun.misc.Unsafe memory allocation. If a backend server sends {"email": null} for a Kotlin property declared as val email: String (non-nullable), Gson will forcefully inject null into that non-nullable field, leading to catastrophic NullPointerExceptions later in your Composables.
Broaden your foundational and advanced Android application development skills across our curriculum:
Connect JSON serialization converters to HTTP client responses.
Serialize nested lists and objects into SQLite text columns.
Define @Serializable data classes with default values.
Parse incoming WebSocket text packets to Kotlin objects.