Swift json deserialize

0

Hello, I have the following code to deserialize a json:

let urlFinal = URLSERVIDOR+"/Geral/consulta?idcliente=\(id)"
        let jsonUrl = urlFinal
        let session = NSURLSession.sharedSession()
        let shotsUrl = NSURL(string: jsonUrl)

        let task = session.dataTaskWithURL(shotsUrl!) {data, response, error in
            guard data != nil else {
                falha()
                return
            }

            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]
                let J = jsonData as! NSDictionary
                let us = J["ServicoCliente"]
                var mstemp = [servicocliente]()
                mstemp <-- us
                dispatch_async(dispatch_get_main_queue(),{
                    sucesso(servs: mstemp)
                });
            } catch _ {
                print("##")
                falha()
            }
        }
        task.resume()

It works very well, but in some specific jsons it has been presenting error, failing in line

let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]

I use the jsonHelper library, but it fails even before the part that uses it (var mstemp = servicoclient; mstemp

asked by anonymous 06.11.2016 / 01:41

1 answer

1

Try using:

    public class func serializeJSON(dictionary: NSDictionary) -> NSData? {
        var data: NSData? = nil
        do {
        data = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
        } catch let error as NSError {
            print("SMCore ->  Error JSON Serialization: \(error) --<<<", terminator: "")
        }
        return data
    }
    
08.11.2016 / 16:28