
JSON to Kotlin Data Class: Complete Guide with kotlinx.serialization, Gson and Moshi
Converting JSON to Kotlin data classes for Android and multiplatform apps. Here's everything you need. Basic Data Class import kotlinx.serialization.Serializable import kotlinx.serialization.SerialName @Serializable data class User ( val id : Int , val name : String , val email : String , val active : Boolean , @SerialName ( "avatar_url" ) val avatarUrl : String ? = null ) // Deserialize val user = Json . decodeFromString < User >( jsonString ) // Serialize val json = Json . encodeToString ( user ) Gson Alternative // build.gradle: implementation 'com.google.code.gson:gson:2.11.0' data class User ( val id : Int , val name : String , @SerializedName ( "avatar_url" ) val avatarUrl : String ? ) val gson = Gson () val user = gson . fromJson ( jsonString , User :: class . java ) val serialized = gson . toJson ( user ) Moshi Alternative // build.gradle: implementation 'com.squareup.moshi:moshi-kotlin:1.15.1' @JsonClass ( generateAdapter = true ) data class User ( val id : Int , val name : St
Continue reading on Dev.to
Opens in a new tab

