How to get listitems in JSONObject

Hello guys,
my JSON is supposed to look like this.
I am using import org.json.JSONObject

{"zip":123, "people":[{"firstname":"Thomas", "lastname":"Tatum"},
{"firstname":"Drew", "lastname":"Uncle"}]}

I have a MutableList, in the List are Person (it’s a data class with firstname and lastname).
But I don’t know how to get my list items in a JSONObject/Array to fit in json (see below).

val json = JSONObject(
                "zip" to 123,
                "people" to //I don't know how to get my values here

Maybe someone can help me.

You have not clarified which json library do you use. Without that information, nobody can help you.


I’ve used kotlinx.serialization.Serializable. It works for me. For example

data class MyPeople(val zip: String, people: List<People>)
data class People(val firstName: String, val lastName: String)

Then you can do Json.encodeToString(myPeople). That will give you the json you described.
Not sure my example is 100% correct. I didn’t actually compile it… just typed it in.

1 Like