iOS Swift Json 序列化中断字符串返回

标签 ios json swift

如果我返回带/不带空格的“test”,它会起作用。但是,当我返回一个用户使用字符串中的返回值存储的值时,它会失败并出现 nil 错误,但是当我查看 NSLog 时,该值就在那里....

失败前的代码

var url:NSURL = NSURL(string:PassURL)!
    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")


    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as! NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

//FAILS HERE
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary

NS日志

2015-07-29 08:52:26.622 testApp[20648:187508] Response ==> {"success":1, "test": "Going to Return Now
Second Line"}
fatal error: unexpectedly found nil while unwrapping an Optional value

但值不是零...

NS错误

Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 41.) UserInfo=0x7f9c9942b050 {NSDebugDescription=Unescaped control character around character 41.})

未转义的字符是return,如何让json接受这个?

最佳答案

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

var error:NSError? = nil

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &error) as? NSDictionary

关于iOS Swift Json 序列化中断字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701171/

相关文章:

c# - 在 Azure Function 中处理从查询到 Azure IOT Hub 的 JSON 响应

macOS 上的 swift : AVAudioPlayer stops immediately

ios - 如何在 Swift 中使用 place_id 从 Google Places API 请求地点详情?

ios - 如何在 RESTkit 0.2 中设置缓存策略

android - 如何在 Android EditText 中显示 iOS 风格的 Emoji 字符?

json - WebHook Azure 数据工厂传递变量

ios - 在 UIImageView 中显示存储在 Firebase 存储(谷歌云)中的图像?

ios - 同一 iPhone/iPad 应用程序的两个版本的图标

ios - 延迟的 OCMock 验证/处理单元测试中的超时

jquery - 使用 ajax 时数据未显示在 Select2 上