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条)

报告相同问题?