JSON does not enter the for Swift2

2

Good, I have this method that reads a JSON from a webservice and stores it in an array.

func conecta(){
let myUrl = NSURL(string: "myWebService");let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";

// Compose a query string
let postString = "username=\(userWS)&password=\(passWS)&servidor=\(servidor)"


request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    if error != nil
    {
        print("error=\(error)")
        return
    }

    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    var err: NSError?
    do{
        let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)




        if let empresas = myJSON["TablaEmp"]!!["item"] as? [[String: AnyObject]] {
            for empresa in empresas {
                let zcif = empresa["Zcif"] as? String
                let zcccp = empresa["Zcccp"] as? String
                let zfax = empresa["Zfax"] as? String
                let zdocu = empresa["Zdocu"] as? String
                self.arrayEmpresas.append([zcif!, zcccp!, zfax!, zdocu!])
            }
        }


        print("muestro: \(self.arrayEmpresas)")

    }catch { print(error)}
}
task.resume()
}

The json is something like that, although bigger, this is the structure.

{"TablaEmp":{"item":[{"Zcif":"123","Zcccp":"456","Zfax":"789","Zdocu":"000"}]}}

It does not give me any error, it just does not enter the for.

The variable myJSON has all the json perfectly, I think it is here where it fails and I do not understand it.

 if let empresas = myJSON["TablaEmp"]!!["item"] as? [[String: AnyObject]] {

Thanks

EDIT :

Debug

tableEmp has "item" but inside is not the "item" content

EDIT2:

I've tried with another code

func conecta(){
    let request = NSMutableURLRequest(URL: NSURL(string: "myWS")!)
    request.HTTPMethod = "POST"
    let postString = "username=\(userWS)&password=\(passWS)&servidor=\(servidor)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }


        let responseString = NSData(data: data!)

        do {
            let jsonDict = try NSJSONSerialization.JSONObjectWithData(responseString, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
            if let jsonDict = jsonDict {

                let jsontabla = jsonDict["TablaEmp"]!["item"]
                print("Cargando array")
                for empresa in jsontabla as! [Dictionary<String, AnyObject>] {

                    let zcif = empresa["Zcif"] as? String
                    let zcccp = empresa["Zcccp"] as? String
                    let zfax = empresa["Zfax"] as? String
                    let zdocu = empresa["Zdocu"] as? String
                    self.arrayEmpresas.append([zcif!, zcccp!, zfax!, zdocu!])


                }
                print("muestro: \(self.arrayEmpresas)")




            } else {
                print("No hay valores")
            }
        } catch let error as NSError {
            print(error)
        }

    }
    task.resume()
}

Could not cast value of type '__NSCFDictionary' (0x10c0ee178) to 'NSArray' (0x10c0edb88).

I do not understand why it is failing, the first code should work perfectly for me. I have done rebuild and clean.

Thanks

    
asked by uWay 18.05.2016 в 10:04
source

1 answer

1

in the first code you are missing this "NSJSONReadingOptions" look.

let myJSON = try NSJSONSerialization.JSONObjectWithData (data !, options: NSJSONReadingOptions.AllowFragments)

    
answered by 25.05.2016 в 16:12