Skip to content

Crash on iOS when encoding/decoding nullable nested data classes #3089

@Merkost

Description

@Merkost

Describe the bug
On real iOS devices, using kotlinx.serialization to encode and decode a @Serializable class containing a nullable nested class crashes the app. This only occurs on physical iOS devices; the same code works on the simulator and on other platforms.

To Reproduce

  1. Create a serializable data class with a nullable nested class and encode it using encodeToString.
  2. Decode the resulting JSON string with decodeFromString.
  3. Run on a physical iOS device.

A minimal reproduction:

@Serializable
data class Outer(
    val id: String,
    val inner: Inner? = null // nullable nested class triggers crash on iOS
)

@Serializable
data class Inner(
    val message: String
)

val json = Json { ignoreUnknownKeys = true }

val encoded = json.encodeToString(Outer.serializer(), Outer("123", Inner("hello")))
// Crash occurs when decodeFromString is called on device:
val decoded = json.decodeFromString(Outer.serializer(), encoded)

The decodeFromString call causes the app to crash on a real iOS device. If inner is made non‑nullable or given a non‑null default instance, the crash disappears.

Expected behavior
encodeToString and decodeFromString should work consistently across platforms. Nullable nested data classes should not cause a crash on iOS.

Environment

  • Kotlin version: 2.2.20
  • kotlinx.serialization version: 1.9.0
  • Kotlin platforms: iOS and Android (Compose Multiplatform)
  • IDE: Android Studio 2025.2.1 Canary 5
  • iOS: occurs on real devices, not simulator.

Additional context
Providing default non‑null values for the nested classes (e.g., using an empty object) seems to avoid the crash. Removing the nullability from the nested class also avoids the crash.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions