Aris Guimerá Aris Guimerá - 6 months ago 24
Swift Question

Json Swift 2 not enter the for

I have this method to read JSON

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()
}


My JSON is anything like that:

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


I have not error, just not enter into my for.

I print my myJSON variable and show perfect JSON, must be this lane I think.

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


Thanks

EDIT:

Debug

enter image description here

tablaEmp have "item" but not enter into the function

EDIT2:

I 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).

Don't understand nothing, my first code must work

FINAL EDIT

I found the problem. When my webservice only return one value, the json is like that:

{"TablaEmp":{"item":{"othervalues":"500","Zcif":"1111"}}}


Without [] and this is the reason that dont work. How can I fix it?

Answer

So far you have posted two demo JSONs and two versions of your code. I have tested both and both work. See the following minimal example:

// let jsonString = "{\"TablaEmp\":{\"item\":[{\"Zcif\":\"123\",\"Zcccp\":\"456\",\"Zfax\":\"789\",\"Zdocu\":\"000\"}]}}"
let jsonString = "{\"TablaEmp\":{\"item\":[{\"othervalues\":\"sssss\",\"Zcif\":\"111\"},{\"othervalues\":\"sssss\",\"Zcif\":\"111\"},{\"othervalues\":\"sssss\",\"Zcif\":\"111\"}]}}"

let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)

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

// code 1
if let empresas = myJSON["TablaEmp"]!!["item"] as? [[String: AnyObject]] {
    for empresa in empresas {
        print("Empresa")
    }
}

// code 2
if let jsonDict = myJSON as? NSDictionary {
    let jsontabla = jsonDict["TablaEmp"]!["item"]
    for empresa in jsontabla as! [Dictionary<String, AnyObject>] {
        print("Empresa")
    }
}

The only possible explanation is that your JSON has a different form. Don't try to find an error in your code, the code is fine for the JSON you have posted. The problem is that the JSON is different.

One solution to handle both single value and multiple values:

let jsonEmpresas = myJSON["TablaEmp"]!!["item"]
let empresas: [[String: AnyObject]]

if let multipleEmpresas = jsonEmpresas as? [[String: AnyObject]] {
    empresas = multipleEmpresas
} else if let singleEmpresa = jsonEmpresas as? [String: AnyObject] {
    empresas = [singleEmpresa]
} else {
    empresas = []
}

// or "for empresa in empresas"
empresas.forEach { empresa in
    let zcif = empresa["Zcif"] as? String
    print(zcif)
}