Response of JSONSerialization.jsonObject is nil wi

2019-08-01 06:01发布

问题:

this is an example for something i want to do but the line if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] is false because the return of JSONSerialization.jsonObject is nil

func parser(lbl: UILabel){
    let postString = "xxx=xxx&xxxx=xxxx==&xxxxx=xxxxx&xxxxxx=xxxxxx&xx=xx"

    let url = URL(string: "http://xxxxxxxxxx.com/xxxxxx/xxxxx/xxxxxx.php")!
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            lbl.text = "error";

            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
                DispatchQueue.main.async {

                    let error = Int(json["success"]!)

                    let message = json["message"]
                    lbl.text = message
                }
            } 
        } catch let parseError {
            print("error to parse: \(parseError)")

            let responseString = String(data: data, encoding: .utf8)
            print("response`enter code here` : \(responseString!)")
        }
    }
    task.resume()
}

回答1:

Try this:

var resultFromServer: Any?
resultFromServer = try JSONSerialization.jsonObject(with: data!, options: [])

This should give you resultFromServer as type of Any?, simply check and typecast depending on the basis of the response you are getting, an array or a dictionary.

Like

if let respdict = resultFromServer as? [String : Any] {
//respone in dictionary format
}

else if let respArr = resultFromServer as? [Any]{
//response is array type
}

else if let stringRespt = String(data: data, encoding: .utf8){
//resp is string                                
}

Just make changes as per your JSON