Handle Nullable JSON Fields in Kotlin Data Classes

Learn how Kotlin's null safety system maps to JSON null values. Covers nullable types, the ? operator, default values for missing fields, and safe access patterns.

Basic Data Classes

Detailed Explanation

Kotlin Null Safety and JSON

Kotlin's type system distinguishes between nullable (String?) and non-nullable (String) types. When JSON fields can be null or absent, you must use nullable types in your data class.

Example JSON

{
  "id": 1,
  "name": "Alice",
  "nickname": null,
  "bio": null,
  "verified": true
}

Generated Kotlin

data class User(
    val id: Int,
    val name: String,
    val nickname: String?,
    val bio: String?,
    val verified: Boolean
)

When to Use Nullable Types

Use ? when:

  • The JSON field can explicitly be null
  • The field may be absent from certain responses
  • The API documentation marks it as optional

Keep non-nullable when:

  • The field is always present and never null
  • You want the deserializer to throw on missing data (fail-fast)

Safe Access Patterns

// Safe call operator
val length = user.nickname?.length

// Elvis operator for defaults
val displayName = user.nickname ?: user.name

// Let block for non-null operations
user.bio?.let { bio ->
    println("Bio: $bio")
}

Nullable vs Default Values

You can combine nullable types with default values to handle missing fields gracefully:

@Serializable
data class User(
    val id: Int,
    val name: String,
    val nickname: String? = null,
    val bio: String? = null,
    val verified: Boolean = false
)

With kotlinx.serialization, fields with defaults can be absent from the JSON without causing errors.

The !! Anti-Pattern

Avoid the not-null assertion operator !! on deserialized data. It defeats Kotlin's null safety and will throw NullPointerException at runtime if the value is null. Prefer ?, ?:, or requireNotNull() with a descriptive message.

Use Case

Database-backed APIs often return null for columns without values. Using nullable Kotlin types lets you distinguish between a user who set their bio to empty and one who never set it at all, which is crucial for correct form handling in Android apps.

Try It — JSON to Kotlin

Open full tool