如何获取 JSONObject 中的列表项?
How to get listitems in JSONObject?
我的 JSON 应该是这样的。
{"zip":123, "people":[{"firstname":"Thomas", "lastname":"Tatum"},
{"firstname":"Drew", "lastname":"Uncle"}]}
(I am using import org.json.JSONObject
)
我有一个 MutableList,列表中有 Person(这是一个数据 class,有名字和姓氏)。
但我不知道如何让 JSON 对象中的列表项适合 json(见下文)。
val json = JSONObject(
mapOf(
"zip" to 123,
"people" to //I don't know how to get my values here
)
)
也许有人可以帮助我。
你可以这样做
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"}]}
}
我的 JSON 应该是这样的。
{"zip":123, "people":[{"firstname":"Thomas", "lastname":"Tatum"},
{"firstname":"Drew", "lastname":"Uncle"}]}
(I am using import org.json.JSONObject
)
我有一个 MutableList,列表中有 Person(这是一个数据 class,有名字和姓氏)。 但我不知道如何让 JSON 对象中的列表项适合 json(见下文)。
val json = JSONObject(
mapOf(
"zip" to 123,
"people" to //I don't know how to get my values here
)
)
也许有人可以帮助我。
你可以这样做
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"}]}
}