How to add mutiple Json Object in Json Array in Kotlin

Viewed 752

I am trying to achieve a json like this :

    {
        "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)
        }
    

Now the value of requestParams which I can receive by the above kotlin code is :

requestParams>> {"input":{"user":"[]"},"token":"eyJ0eXAiOiJKV1QiLCJjdHkiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ZXlKMGVYQWlPaUpLVjFRaUxDSmxibU1pT2lKQk1USTRRMEpETFVoVE1qVTJJaXdpW"}
    

It is not adding json objects in "input" json array. Can anyone help me why I am getting empty "input" array? Note: while debugging I can see the values of KEY_SECURITY_QA and KEY_SECURITY_QA_KEY.

1 Answers

The reason your code is not working is you are missing put inside the Array.

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)
                })
            }
        )
    }

Also You are mixing the Json packages . JSONObject and JSONArray are from org.json and JsonObject and JsonArray are from Gson . you should be using one of them not both.

An easy way to do this to just create a Pojo class and Create the JsonObject with the help of Gson .

Related