Created
April 10, 2019 07:29
-
-
Save vbsteven/38ab2d880a372a432df242ba91d8fe9c to your computer and use it in GitHub Desktop.
Kotlinx.deserialization example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
buildscript { | |
ext.kotlin_version = '1.3.21' | |
repositories { | |
jcenter() | |
} | |
dependencies { | |
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.21" | |
classpath "org.jetbrains.kotlin:kotlin-serialization:1.3.21" | |
} | |
} | |
plugins { | |
id 'org.jetbrains.kotlin.jvm' version '1.3.21' | |
} | |
apply plugin: 'kotlin' // or 'kotlin-multiplatform' for multiplatform projects | |
apply plugin: 'kotlinx-serialization' | |
group 'io.quantus' | |
version '1.0-SNAPSHOT' | |
repositories { | |
mavenCentral() | |
jcenter() | |
maven { url "https://kotlin.bintray.com/kotlinx" } | |
} | |
dependencies { | |
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" | |
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" | |
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.10.0" | |
} | |
compileKotlin { | |
kotlinOptions.jvmTarget = "1.8" | |
} | |
compileTestKotlin { | |
kotlinOptions.jvmTarget = "1.8" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.serialization.SerialName | |
import kotlinx.serialization.Serializable | |
import kotlinx.serialization.Transient | |
import kotlinx.serialization.json.Json | |
val json = """ | |
{ | |
"History": | |
[ | |
{"Added": 2000} | |
] | |
} | |
""" | |
@Serializable | |
data class History( | |
@SerialName("Added") | |
val addedTimeInSeconds : Long | |
) { | |
init { | |
println("### in init $addedTimeInSeconds") | |
} | |
@Transient | |
val addedTimeInMillis : Long = addedTimeInSeconds * 1000 | |
} | |
@Serializable | |
data class HistoryResponse( | |
@SerialName("History") | |
val historyList: List<History> | |
) | |
fun main() { | |
val response = Json.parse(HistoryResponse.serializer(), json) | |
println(response) | |
println("added time in millis ${response.historyList.first().addedTimeInMillis}") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### in init 2000 | |
HistoryResponse(historyList=[History(addedTimeInSeconds=2000)]) | |
added time in millis 2000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment