Hello,
This code Kotlin Playground: Edit, Run, Share Kotlin Code Online tests the kotlinx.serialization
Mostly, the output is:
{"name":"Alice","age":30,"swtK":false,"now3":1741025383879}
{"name":"David","age":32,"now3":1741025383922}
User(name=Alice, age=30, swtK=false)
User(name=David, age=32, swtK=true)
Very rarely, the output is like shown in the screenshot.
{"name":"Alice","age":30,"swtK":false,"now3":1740944237946,"now4":1740944237,"now5":1740944237}
{"name":"David","age":32,"now3":1740944237996,"now4":1740944237,"now5":1740944237}
User(name=Alice, age=30, swtK=false)
User(name-David, age=32, swtK=true)
-
Why are the properties now4 and now5 not encoded (encodeToString)?
-
Why are the boolean properties (swtK) not decoded (decodeFromString) when the value is TRUE?
-
How to use/import io.realm.kotlin.* to test it?
-
What is your recommendation to save the creation timestamp (second or millisecond from 1.1.1970) of a new record?
Thanks
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import java.time.Instant
import java.util.Calendar
import java.util.Date
//import io.realm.kotlin.ext.query
//import io.realm.kotlin.serializers.RealmInstantKSerializer
//import io.realm.kotlin.types.RealmInstant
//import io.realm.kotlin.types.RealmObject
//import io.realm.kotlin.types.annotations.PrimaryKey
@Serializable
data class User(var name:String, var age:Int, var swtK:Boolean=true){
//@Transient
//@PrimaryKey
//var idPK:ObjectId=ObjectId()
//@Serializable(RealmInstantKSerializer::class)
//var nowK:RealmInstant=RealmInstant.now()
//var now2:Long=RealmInstant.now().toInstant().epochSecond
var now3:Long=Calendar.getInstance().timeInMillis
var now4:Long=Instant.now().epochSecond
var now5:Long=Date().toInstant().epochSecond
constructor():this(name="", age=0, swtK=true)
companion object
}
fun main() {
var line=""
lateinit var user:User
val alice=User("Alice", 30, false)
val david=User("David", 32, true)
val listU:List<User> =listOf(alice, david)
val convStr=mutableListOf<String>()
listU.forEach {item ->
line=Json.encodeToString(item)
convStr.add(line)
println(line)
}
convStr.forEach {item ->
user=Json.decodeFromString<User>(item)
println(user)
}
}