Skip to content

Instantly share code, notes, and snippets.

@muchbeer
Last active February 10, 2022 12:49
Show Gist options
  • Select an option

  • Save muchbeer/fa73ce11b909f75d1ce9d08fc32f25ca to your computer and use it in GitHub Desktop.

Select an option

Save muchbeer/fa73ce11b909f75d1ce9d08fc32f25ca to your computer and use it in GitHub Desktop.
Serialization help improve reading the data class model and simplify the json cool stuff More information : https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md and from Kotlin documentation: https://blog.jetbrains.com/kotlin/2020/10/kotlinx-serialization-1-0-released/
//*************************When using with Retrofit please use below converter*************************************
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0")
//A Retrofit 2 Converter.Factory for Kotlin serialization.
val contentType = "application/json".toMediaType()
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com/")
.addConverterFactory(Json.asConverterFactory(contentType))
.build()
//**************************Dependency gradle*******************************
plugins {
id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.10'
}
buildscript {
ext.kotlin_version = '1.6.10'
repositories { mavenCentral() }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
}
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2"
}
/*
otlinx.serialization comes with a simple but powerful pure-Kotlin API, which makes it effortless to parse JSON into type-safe
Kotlin objects, and vice versa.
*/
@Serializable
data class User(val name: String, val yearOfBirth: Int)
fun main() {
// Serialization (Kotlin object to JSON string)
val data = User("Louis", 1901)
val string = Json.encodeToString(data)
println(string) // {"name":"Louis","yearOfBirth":1901}
// Deserialization (JSON string to Kotlin object)
val obj = Json.decodeFromString<User>(string)
println(obj) // User(name=Louis, yearOfBirth=1901)
}
/*
Whether you’re trying to serialize a data class with default initializers for its properties,
a singleton object, or trying to deserialize a generic List<T>: kotlinx.serialization always
behaves as you would expect.
*/
@Serializable
data class Project(
val name: String,
val owner: Account,
val group: String = "R&D"
)
@Serializable
data class Account(val userName: String)
val moonshot = Project("Moonshot", Account("Jane"))
val cleanup = Project("Cleanup", Account("Mike"), "Maintenance")
fun main() {
val string = Json.encodeToString(listOf(moonshot, cleanup))
println(string)
// [{"name":"Moonshot","owner":{"userName":"Jane"}},{"name":"Cleanup","owner":{"userName":"Mike"},"group":"Maintenance"}]
val projectCollection = Json.decodeFromString<List<Project>>(string)
println(projectCollection)
// [Project(name=Moonshot, owner=Account(userName=Jane), group=R&D), Project(name=Cleanup, owner=Account(userName=Mike), group=Maintenance)]
}
/*
As you can see, even the type-safe deserialization of collections with generics is handled by kotlinx.serialization just as expected.
This certainly isn’t the norm,
*/
************gradle.build*******************
buildscript {
ext {
compose_version = '1.1.0-rc01'
kotlin_version = '1.6.0'
}
dependencies {
// Other classpath declarations
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
**************gradle.build**************************
plugins {
id 'kotlinx-serialization' version "1.4.0"
}
dependencies {
// KotlinX Serialization
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
}
****************************Comparing Kotlin Serialization Library to Moshi and Gson ********************************
//Better support for Kotlin’s type system compared to Gson, including support for nullable and default values.
//Support for many encoding formats through the use of separate library modules.
*************ENCODING*******************8
@Serializable
class Project(val name: String, val language: String)
fun main() {
val data = Project("kotlinx.serialization", "Kotlin")
println(Json.encodeToString(data))
}
Output -> {"name":"kotlinx.serialization","language":"Kotlin"}
****************DECODING*********************
@Serializable
data class Project(val name: String, val language: String)
fun main() {
val data = Json.decodeFromString<Project>("""
{"name":"kotlinx.serialization","language":"Kotlin"}
""")
println(data)
}
Output-> Project(name=kotlinx.serialization, language=Kotlin)
**************BACKING FIELDS******************8
//Only a class's properties with backing fields are serialized, so properties with a getter/setter that don't have a backing field
//and delegated properties are not serialized, as the following example shows.
@Serializable
class Project(
// name is a property with backing field -- serialized
var name: String
) {
var stars: Int = 0 // property with a backing field -- serialized
val path: String // getter only, no backing field -- not serialized
get() = "kotlin/$name"
var id by ::name // delegated property -- not serialized
}
fun main() {
val data = Project("kotlinx.serialization").apply { stars = 9000 }
println(Json.encodeToString(data))
}
//We can clearly see that only the name and stars properties are present in the JSON output.
Output -> {"name":"kotlinx.serialization","stars":9000}
*******Reference Object********************
Serializable classes can reference other classes in their serializable properties. The referenced classes must be also marked as @Serializable.
@Serializable
class Project(val name: String, val owner: User)
@Serializable
class User(val name: String)
fun main() {
val owner = User("kotlin")
val data = Project("kotlinx.serialization", owner)
println(Json.encodeToString(data))
}
//When encoded to JSON it results in a nested JSON object.
Output -> {"name":"kotlinx.serialization","owner":{"name":"kotlin"}}
//The library can serialize all primitive Kotlin values out of the box, including Boolean, Byte, Short, Int, Long, Float, Double, Char and String. It also supports composite types based on these primitives, such as List, Map, Set, Pair and Triple. enums work automatically, too!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment