Search code examples
swift3alamofire

Sending JSON data in the body of an Alamofire Request


I'm trying to make an api call to submit some data using Alamofire (version 4.0). The trouble i'm having is that when making the call I get a response from the server that the JSON data was not in a valid format.

Is there a way to check if the data data is being serialized correctly in Alamofire?

I have tried many of the solutions currently on StackOverflow and cannot find a solution. Thanks for your help.

This should be the format of the request body:

{
"reference_id": "Test001",
"data": {
    "type": "step",
    "data": {
        "2015-08-02": 8574
    }
}
}

My Swift code:

let params: [String:Any] = [
        "reference_id": "someName",
        "data": [
            "type" : "step",
            "data": [
                "2015-08-02": 8574
            ]
        ]
    ]

    print(params)

    if let userToken = userToken {
        let request = Alamofire.request(url+"API.php?Action=SaveHealthData", method: .post, parameters: params, encoding: JSONEncoding.default).responseString(completionHandler: { response in
            print(response)
        })
    }

The error I'm getting is:

Warning: json_decode() expects parameter 1 to be string, array given in /var/www/html/API/SaveHealthData.php on line 8
{"error":"data not in valid json format"}


Solution

  • Here is the solutions of your problem,

    var dataDict : [String : Any] = [:];
    
    dataDict["type"] = "Step"
    dataDict["data"] = ["2015-08-02": 8574];
    
    let params: [String:Any] = ["reference_id": "someName",
                                "data": String.toJSonString(data: dataDict)];
    

    Here toJSonString is an extension of String

    static func toJSonString(data : Any) -> String {
    
            var jsonString = "";
    
            do {
    
                let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
                jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
    
            } catch {
                print(error.localizedDescription)
            }
    
            return jsonString;
    }
    

    Happy Coding