Search code examples
jsonswiftnsarraynsdictionary

Facing Problem in encoding array of dictionary to JSON


In POST request I have to send following JSON data

{
    "users": [{"userid": 16, "meetAt":"Some place (College/trip etc)", "showFields": "11111111000"}, {"userid": 17, "meetAt":"Some place (College/trip etc)", "showFields": "11111111001"}]
}

I am trying

static func linkRequestBody(userDetails: ScannedContact) -> Any
{

    let jsonToRegistrer =  [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]];
    return jsonToRegistrer;
}

I can see in debugger that userDetails.id and userDetails.showFields have valid value but still it fails.

ERROR:

{"":["The input was not valid."]}

Solution

  • That's your target format:

    {
        "users": [{
            "userid": 16,
            "meetAt": "Some place (College/trip etc)",
            "showFields": "11111111000"
        }, {
            "userid": 17,
            "meetAt": "Some place (College/trip etc)",
            "showFields": "11111111001"
        }]
    }
    

    After calling JSONSerialization on it (or if your code accept a Dictionary/Array and do the translation itself):

    let jsonToRegistrer =  [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]];
    

    Should represent that:

    [{
        "userid": 16,
        "meetAt": "Defalut Test Location at",
        "showFields": "11111111000"
    }]
    

    You see the issue? Your version is an Array and the target one is a Dictionary and you are so missing the users key.

    To fix it:

    let jsonToRegistrer =  ["user": [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]]];
    

    You can also not write it in one line to be clearer:

    let jsonToRegistrer = ["user": [
                                     ["userid": userDetails.id,
                                      "meetAt": "Defalut Test Location at",
                                      "showFields": userDetails.showFields]
                                    ]
                            ];
    

    So the issue is that your version didn't have the same format at the one needed.

    To see what's your version rendered in JSON you can use:

    let jsonData = try? JSONSerialization.data(withJSONObject: jsonToRegistrer, options: .prettyPrinted)
    let jsonString = String(data: jsonData!, encoding: .utf8) //Note it's a force unwrap but just to debug, avoid using force unwrap
    print("jsonString: \(jsonString)")