我正在尝试实现这样的 json :
{
"input": {
"user":[
{
"queId":"SEQ2001",
"answer":"car"
},
{
"queId":"SEQ2008",
"answer":"bus"
}
]
},
"token": "{{token}}"
}
My current code for it in Kotlin is as follows:
requestParams = JSONObject().apply {
put(
KEY_INPUT,
JSONObject().apply {
put(
KEY_USER,
JsonArray().apply {
JSONObject().apply {
put(KEY_SECURITY_QA, qa1Key)
put(KEY_SECURITY_QA_KEY, qa1)
}
JSONObject().apply {
put(KEY_SECURITY_QA, qa2Key)
put(KEY_SECURITY_QA_KEY, qa2)
}
}
)
}
)
put(KEY_TOKEN, appToken?.jwtToken)
}
现在我可以通过上面的 kotlin 代码接收到的 requestParams 的值是:
requestParams>> {"input":{"user":"[]"},"token":"eyJ0eXAiOiJKV1QiLCJjdHkiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ZXlKMGVYQWlPaUpLVjFRaUxDSmxibU1pT2lKQk1USTRRMEpETFVoVE1qVTJJaXdpW"}
它没有在“input”json 数组中添加 json 对象。谁能帮助我为什么我得到空的“输入”数组?注意:调试时我可以看到 KEY_SECURITY_QA 和 KEY_SECURITY_QA_KEY 的值。
最佳答案
您的代码无法正常工作的原因是您在 Array
中缺少 put
。
JSONObject().apply {
put(
"user",
JSONArray().apply {
put(JSONObject().apply {
put(KEY_SECURITY_QA, qa1Key)
put(KEY_SECURITY_QA_KEY, qa1)
})
put(JSONObject().apply {
put(KEY_SECURITY_QA, qa2Key)
put(KEY_SECURITY_QA_KEY, qa2)
})
}
)
}
此外,您正在混合 Json 包。 JSONObject
和 JSONArray
来自 org.json
,JsonObject
和 JsonArray
来自 Gson
。您应该使用其中之一而不是两者。
执行此操作的简单方法是创建一个 Pojo 类并在 Gson
的帮助下创建 JsonObject
。
关于android - 如何在 Kotlin 中的 Json 数组中添加多个 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71779702/