dongshuofu0039 2019-04-13 22:01
浏览 148
已采纳

为什么我的php json_encode不能在alamofire中使用.responseJSON进行序列化?

I'm having some trouble with serialization on a JSON response on my iOS app from my server, its a PHP back-end. My app sends a post request with the appropriate parameters, validates them, puts the results in an array, and encodes it in. Now that's not the problem, code works fine. However, its the link between them. Look at the PHP code below.

echo json_encode($array)

Now coming to xcode, I'm using alamofire to send the request as seen in the code below

Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseString { response in
            print(response)
            }
        }

As you can see its in .responseString because I apparently if I use .responseJSON it throws a code=3480 error and I want to get specific data from my own response JSON. I tried other ways to fix this online, but they all choose the .responseString option.

Why is this happening? Are the JSON types incompatible? Is there a secret to this?

I just want to get specific data from my JSON response such as "message" and its not possible when i get a string... Any help is appreciated!

I'm using Alamofire 4.3

  • 写回答

2条回答 默认 最新

  • dqlb38410 2019-04-13 22:35
    关注

    Try following so Alamofire will run the response data through JSONSerialization, depending on the type of JSON response you can use either json as? [String : Any] or json as? [[String : Any]]

    Alamofire.request(URL, method: .post, parameters: parameters).responseJSON { response in
        guard response.error == nil, let json = response.result.value else {
            print("Error: \(response.error?.localizedDescription ?? "no content")")
            return
        }
    
        if let jsonDict = json as? [String : Any] {
            print(jsonDict)
        } else if let jsonArray = json as? [[String : Any]] {
            print(jsonArray)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?