Swift - NSJsonSerialization - "无法将数据转换为字符串周围的字符串"错误

时间:2015-12-23 21:46:13

标签: ios json swift

当我尝试使用字典作为参数发布网址时出现以下错误;

  

NSCocoaErrorDomain Code = 3840"无法将数据转换为字符串   角色34

我的代码如下;

    func postOrder() {

    let params = [
        “date”: ”25.12.2015”,
        “time” : “22:34”,
        “order_no”: “23232322”,
        "user_id" : “23232”
           ] as Dictionary<String, String>

    let request = NSMutableURLRequest(URL: NSURL(string: "http://webservis.xxxxx.com/post_order.asp")!)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

    let task = session.dataTaskWithRequest(request) { data, response, error in

       guard data != nil else {
            print("no data found: \(error)")
            return
        }

        let cfEnc = CFStringEncodings.ISOLatin5
        let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

        let outputString = NSString(data: data!, encoding: enc)


        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                let success = json["success"] as? Int                                  
                print("Success: \(success)")
            } else {

                let cfEnc = CFStringEncodings.ISOLatin5
                let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

                let jsonStr = NSString(data: data!, encoding: enc)   
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)                                                        

            let cfEnc = CFStringEncodings.ISOLatin5
            let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

            let jsonStr = NSString(data: data!, encoding: enc)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume()

}

上述代码有什么问题,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

检查您正在解析的数据是否实际上是有效的JSON(而不仅仅是'几乎'JSON)。当您有不同的数据格式无法解析为JSON时,就会发生该错误。

用以下内容替换params,然后重试。

let params = [
        "date": "25.12.2015",
        "time" : "22:34",
        "order_no": "23232322",
        "user_id" : "23232"
           ] as Dictionary<String, String>

此外,您可以查看以下主题iOS 5 JSON Parsing Results in Cocoa Error 3840