Home > Back-end >  How to get listitems in JSONObject?
How to get listitems in JSONObject?

Time:05-21

my JSON is supposed to look like this.

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

(I am using import org.json.JSONObject)

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 to fit in json (see below).

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

Maybe someone can help me.

CodePudding user response:

You could do this

import org.json.JSONObject

data class Person(val firstname: String, val lastname: String)

fun main() {
    val people = arrayOf(Person("Thomas", "Tatum"), Person("Drew", "Uncle")) //also works for Lists, doesn't need to be an array
    val json = JSONObject(
        mapOf(
            "zip" to 123,
            "people" to people,
        )
    )
    println(json)
    //prints: {"zip":123,"people":[{"firstname":"Thomas","lastname":"Tatum"},{"firstname":"Drew","lastname":"Uncle"}]}
}
  • Related