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)
}
In 2019 no-one is really parsing JSON manually. It's much easier to use Gson library. It takes as an input your object and spits out JSON string and vice-versa.
Example:
data class MyClass(@SerializedName("s1") val s1: Int)
val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)
This way you're not working with JSON string directly but rather with Kotlin object which is type-safe and more convenient. Look at the docs. It's pretty big and easy to understand
Here is some tutorials:
- https://www.youtube.com/watch?v=f-kcvxYZrB4
- http://www.studytrails.com/java/json/java-google-json-introduction/
- https://www.tutorialspoint.com/gson/index.htm
UPDATE: If you really want to use JSONObject then use its constructor with a string parameter which parses your JSON string automatically.
val jsonObject = JSONObject(data)
Best way is using kotlinx.serialization. turn a Kotlin object into its JSON representation and back marking its class with the @Serializable annotation, and using the provided encodeToString and decodeFromString<T> extension functions on the Json object:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class User(val name: String, val yearOfBirth: Int)
// 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)
Further examples: https://blog.jetbrains.com/kotlin/2020/10/kotlinx-serialization-1-0-released/