slysysl slysysl - 3 months ago 8
JSON Question

unexpectedly found nil while unwrapping an Optional value while converting JSON Array

while I try to convert Json String to Dictionary it gives me fatal eror: unexpectedly found nil while unwrapping an Optional value.

self.res = Jsn.convertStringToDictionary(self.sub)!


sub = [{"CityId":6,"CityName":"Ankara"},{"CityId":34,"CityName":"─░stanbul"}]

And the function is:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String:AnyObject]
} catch {
print(error)
}
}
return nil
}


Can you help me with the problem. Thank you in advance!

Answer

You should convert it to [[String:AnyObject]] instead of [String:AnyObject] because it is array of dictionaries.

Try using

return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [[String:AnyObject]]
Comments