JSON to Kotlin Data Class
Generate Kotlin data classes from JSON. Supports kotlinx.serialization, Gson, and Moshi annotations with proper type inference.
Features
đ¯ Idiomatic Kotlin
- Data class generation
- Proper Kotlin type mapping
- Nested class support
- Null-safe types with ?
đĻ Multiple Libraries
- kotlinx.serialization
- Gson annotations
- Moshi annotations
- Automatic @SerialName
⥠Smart Type Inference
- Int vs Double detection
- List<T> for arrays
- Nested object classes
- Optional nullable fields
Kotlin Data Class Guide
Kotlin Data Classes with Serialization
Kotlin data classes are the idiomatic way to model JSON data. With kotlinx.serialization, you get compile-time safe serialization.
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
data class User(
val id: Int,
val name: String,
@SerialName("is_active")
val isActive: Boolean
)
Making generated Kotlin data classes robust
Kotlin serialization libraries fail loudly when JSON does not match the declared types. That is useful, but it means a generated data class should be reviewed against the real range of data your app will receive.
Tips and common pitfalls
- Mark fields nullable (
String?) when the API can omit them or sendnull, and give them a default ofnull. - With kotlinx.serialization, configure
Json { ignoreUnknownKeys = true }so new server fields do not crash older app versions. - Use
Longrather thanIntfor IDs and counters that can exceed about 2.1 billion. - Map fixed string values to an
enum classwith@SerialNameon each constant.
More questions
Which library should I use on Android?
kotlinx.serialization is the Kotlin-first choice and works well with Ktor and Retrofit converters. Moshi and Gson remain common in older codebases; Moshi handles Kotlin nullability better than Gson.
How do I handle a field that is sometimes a string and sometimes a number?
Declare it as JsonElement and read it manually, or write a custom serializer. Better still, ask the API owner to use one type consistently.