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 服务器一块硬盘重启过程中安装后,硬盘不识别了怎么修复?
  • ¥15 微信红包不拆包 知道红包金额
  • ¥15 0基础学机器人运动控制要多久?
  • ¥15 .net core 怎么进行中英文转换
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?