尝试POST时“无效的JSON”

时间:2018-02-14 04:14:55

标签: json swift post swifty-json

我正在尝试将json数据发布到Booking Service API。

但是当我点击提交时,我收到 400错误,从而产生“INVALID JSON”消息。

let urlToRequest = "https://api.bookeo.com/v2/customers?secretKey=" + secretKey + "&apiKey=" + apiKey

func dataRequest() {
        let url4 = URL(string: urlToRequest)!
        let session4 = URLSession.shared
        let request = NSMutableURLRequest(url: url4)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData


        let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: newParameters)
        request.httpBody = dataParameters
        //request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("api.bookeo.com", forHTTPHeaderField: "Host")
        request.addValue("Keep-Alive", forHTTPHeaderField: "Connection")
        request.addValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")


        let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
            if let response = response {
                print(response)
            }
            if let data = data {
                do {
                    let json = try? JSONSerialization.jsonObject(with: data, options: [])
                    print(json as Any)
                } //catch {
                    //print(error)
                //}

            }


            let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("*****This is the data 4: \(String(describing: dataString))") //JSONSerialization
        }
        task.resume()

    }
    dataRequest()

我的参数:(“无效的JSON”)

let parameters: Parameters = [
        "eventId": eventId,
        "customer": [
            "firstName": FirstName.text!,
            "lastName": LastName.text!,
            "emailAddress": EmailAddress.text!,
            "phoneNumbers": [
                "number": "123456",
                "type": "mobile"
            ]
        ],
        "participants": [
            "numbers": [
            "peopleCategoryId": peopleCategoryId,
            "number": 1
        ],
    ],
        "productId": productId,
        "initialPayments": [
            "reason": "Initial deposit",
            "comment": "This is a custom comment",
            "amount": [
                "amount": "0",
                "currency": "USD"
            ],
        "paymentMethod": "creditCard"
        ]
        ] as [String : Any]

我的错误回复:

*****This is the data 4: Optional({
"httpStatus": 400,
"message": "Invalid JSON",
"errorId": "1555Q180214041018NWE6T"
})

在使用格式相同的JSON之前,我已经使用过这个确切的方法。所以我无法弄清楚为什么这不起作用。

1 个答案:

答案 0 :(得分:0)

这是你的问题:

NSKeyedArchiver.archivedData

不要使用JSONSerialization.data来序列化json;它以完全不同于json的方式序列化对象。

选项#1

改为使用let jsonDictionary = [ "testObject": [ "1": 2", "3": "4"]] let jsonData = try JSONSerialization.data(withJSONObject:jsonDictionary, options:.prettyPrinted)

Codable

选项#2

制作符合struct Parameters: Codable { let value1: String let value2: String } 协议的结构:

let parameters = Parameters(value1: "test1", value2: "test2")
let jsonData = try jsonEncoder.encode(parameters)

以这种方式序列化:

jsonData

进一步说明:

要验证print(String(data: jsonData, encoding: .utf8)) 是否符合预期,请使用以下代码:

grep '\bth.[aeiouy]*\b' filename.txt

这会将json作为字符串打印到控制台,这样您就可以验证json是否有效并满足服务器端期望。