There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released
https://github.com/Kotlin/kotlinx.serialization
Copyimport kotlinx.serialization.*
import kotlinx.serialization.json.Json
@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")
fun main(args: Array<String>) {
// serializing objects
val jsonData = Json.encodeToString(MyModel.serializer(), MyModel(42))
println(jsonData) // {"a": 42, "b": "42"}
// serializing lists
val jsonList = Json.encodeToString(MyModel.serializer().list, listOf(MyModel(42)))
println(jsonList) // [{"a": 42, "b": "42"}]
// parsing data back
val obj = Json.decodeFromString(MyModel.serializer(), """{"a":42}""")
println(obj) // MyModel(a=42, b="42")
}
Answer from Elisha Sterngold on Stack OverflowVideos
There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released
https://github.com/Kotlin/kotlinx.serialization
Copyimport kotlinx.serialization.*
import kotlinx.serialization.json.Json
@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")
fun main(args: Array<String>) {
// serializing objects
val jsonData = Json.encodeToString(MyModel.serializer(), MyModel(42))
println(jsonData) // {"a": 42, "b": "42"}
// serializing lists
val jsonList = Json.encodeToString(MyModel.serializer().list, listOf(MyModel(42)))
println(jsonList) // [{"a": 42, "b": "42"}]
// parsing data back
val obj = Json.decodeFromString(MyModel.serializer(), """{"a":42}""")
println(obj) // MyModel(a=42, b="42")
}
You can use this library https://github.com/cbeust/klaxon
Klaxon is a lightweight library to parse JSON in Kotlin.
I can see that you want to serialize the ArrayList<UserPatient>. You can do it easily with Gson.
Example:
val response = AccountInfoResponse(/* Here goes the objects that is needed to create instance of this class */)
val jsonString = Gson().toJson(response.userpatients)
Output:
{"userpatients":[{"sex":"male","date of birth":"2010-01-03","image":"","clinics":[1],"primary_provider":[{"clinic":1,"patient":1,"providers":1}],"role":"patient","last name":"John","address":"300 east main st. San Jose, Ca 95014","first name":"John","username":"John","email":"[email protected]","mobile":"+88083918427"}],"userpatients":[{"sex":"female","date of birth":"2000-01-01","address":"fawal st1","patientID":1,"first name":"john","clinicName":"light house peds","clinicID":1,"mobile":"8056688042","last name":"john"}]}
inspired by previous answer I enabled it to recognize all fields null valued included :
val builder = GsonBuilder()
builder.serializeNulls()
val gson = builder.setPrettyPrinting().create()
val json= gson.toJson(obj)
if (BuildConfig.DEBUG) {
Log.i("@@@!", "myjson " + json)
}