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 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势