Swift - NSJsonSerialization - “无法将数据转换为围绕字符的字符串”错误

Posted

技术标签:

【中文标题】Swift - NSJsonSerialization - “无法将数据转换为围绕字符的字符串”错误【英文标题】:Swift - NSJsonSerialization - "Unable to convert data to string around character" error 【发布时间】:2015-12-23 21:46:12 【问题描述】:

尝试发布带有字典作为参数的 url 时出现以下错误;

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】:

检查您正在解析的数据是否实际上是有效的 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

【讨论】:

以上是关于Swift - NSJsonSerialization - “无法将数据转换为围绕字符的字符串”错误的主要内容,如果未能解决你的问题,请参考以下文章

swift [Swift Notes]在学习Swift #Swift的同时收集笔记

Swift 反射

Swift入门系列--Swift官方文档(2.2)--中文翻译--About Swift 关于Swift

swift 示例BS swift.swift

swift swift_bug.swift

ios 整理(一)swift和oc的区别