android - 如何在 Kotlin 中的 Json 数组中添加多个 Json 对象

标签 android arrays json kotlin

我正在尝试实现这样的 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 包。 JSONObjectJSONArray 来自 org.jsonJsonObjectJsonArray 来自 Gson 。您应该使用其中之一而不是两者。

执行此操作的简单方法是创建一个 Pojo 类并在 Gson 的帮助下创建 JsonObject

关于android - 如何在 Kotlin 中的 Json 数组中添加多个 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71779702/

相关文章:

Java应用卡通效果

android - Aapt错误-1073741816

javascript - JavaScript typeof 曾经返回过 "array"吗?

java - 比较数组条目

arrays - Ruby:哈希数组 - 如何根据作为数组的哈希键删除重复项

javascript - 经过验证的JSON抛出SyntaxError : Property must be a string literal

java - 唱歌后在 Android 应用程序中保持 session 的最佳方式?

javascript - 饼图未使用远程存储呈现(使用静态存储)

python - 如何将流文件传递给执行Python脚本并使用属性和Nifi变量来存储该文件?

android - 找不到 org.codehaus.groovy :groovy-all:2. 4.12