gpt4 book ai didi

ios - Swift - NSJsonSerialization - "Unable to convert data to string around character"错误

转载 作者:行者123 更新时间:2023-11-30 13:49:41 26 4
gpt4 key购买 nike

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

NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 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()

}

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

最佳答案

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

关于ios - Swift - NSJsonSerialization - "Unable to convert data to string around character"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com