【问题标题】:Alamofire JSON response with strange characters in SwiftSwift 中带有奇怪字符的 Alamofire JSON 响应
【发布时间】:2015-10-28 12:19:41
【问题描述】:

我正在使用 Alamofire 3.0 和 swift 2,并从以下请求中得到一个奇怪的响应:

func requestURLwithHeadersAndParams(URLstr:String, connectionMethod: Alamofire.Method, header: [String : String], body:[String : AnyObject], completion: (reponse: String, statusCode: Int, error: String) -> Void)  {        
///Singleton Alamofire connection manager
let alamofireManager = Alamofire.Manager.sharedInstance
alamofireManager.request(connectionMethod, URLstr, parameters: body, encoding: ParameterEncoding.JSON, headers: header).responseJSON (){
        response in

        print("\nSuccess: \(response.result.isSuccess)")

        switch response.result {
        case .Success(let value):
            print("Response Status code: \((response.response?.statusCode)!)\n")
            print("\(value)")
            completion(reponse: "\(value)" , statusCode: (response.response?.statusCode)! , error: "")

        case .Failure(let error):
            print("Error Code:\(error.code) - Description:\(error.localizedDescription)")
            completion(reponse: "Error" , statusCode: (response.response?.statusCode)!, error: error.localizedDescription)

        } } }

value 属性包含:

"{\n    \"auth_token\" = \"qcW-mQmyX8ototieJu7WK\";\n    avatar =     {\n        standard =         {\n            url = \"<null>\";\n        };\n        url = \"<null>\";\n    };\n    birthdate = \"<null>\";\n    \"created_at\" = \"2015-10-28T07:02:20.445Z\";\n    email = \"elrope@abt.com\";\n    \"first_name\" = El;\n    id = 12;\n    \"last_name\" = Perro;\n    role = user;\n    \"shooter_type\" = \"\";\n    \"updated_at\" = \"2015-10-28T07:42:37.860Z\";\n}"

知道如何摆脱所有转义字符('\' 和 '\n'),因为在调用此方法的方法中使用 SwiftyJSON 的 JSON 序列化无法将字符串识别为 json 字符串并且在我做let json = JSON(reponse) 有错误:

错误域=SwiftyJSONErrorDomain 代码=901 "字典["auth_token"] 失败,它不是字典” UserInfo=0x6030002d7c00 {NSLocalizedDescription=Dictionary["auth_token"] 失败,它不是 字典})

【问题讨论】:

  • 我很好奇。编译器说这个值是什么类型?
  • reponse: "\(value)" 为什么?你为什么这样做?为什么你希望它是一个字符串?如果您希望它是一个字符串,请使用responseString,而不是responseJSON (stackoverflow.com/questions/44095161/…)。您正在调用 description 我们可以猜测的是一个 JSON,其顶层是一个已经解析的字典。

标签: swift alamofire


【解决方案1】:

我发现您的 JSON 本身无效。 例如avatarstandard 不是字符串,引号在哪里?

我相信使用,: 比使用;= 更好

我在 SwiftyJSON 上进行了测试,经过上述更改后一切正常。所以也许问题出在你的后端。尝试使用网络浏览器验证原始 JSON。

【讨论】:

  • 我在调用中将 Alamofire 从 responseJSON() 更改为 response() 并完成:请求、响应、数据、错误而不是响应。现在数据没问题,我可以使用 SwiftyJSON 正确序列化它,但仍然不清楚为什么我之前从 Alamofire responseJSON() 收到了该响应。可能是 Alamofire 中的错误?
【解决方案2】:

您的 JSON 无效。

实际上,您的 value 字符串只不过是 NSDictionary 的 .description 输出!

游乐场演示:

不用说这不是 JSON ......所以当你尝试将它提供给 SwiftyJSON 时它当然会失败。

所以,要么你在某个地方感到困惑,要么使用字典的 描述 而不是它的实际内容......

...或者这个错误来自服务器。

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多