-1

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!

slytrkmn
  • 272
  • 1
  • 4
  • 15
  • Show your actual response which is coming from server. – Dharmesh Kheni Aug 04 '16 at 12:13
  • The function comes from http://stackoverflow.com/a/30480777/2227743 and is named `convertStringToDictionary`. Your JSON is an *array* of dictionaries... – Eric Aya Aug 04 '16 at 12:28
  • Also, this function returns an Optional *for a reason*. If you force-unwrap the result on the caller side instead of handling the Optional, of course your app will crash. – Eric Aya Aug 04 '16 at 12:34
  • @EricAya I am new with swift thank you for your answers. – slytrkmn Aug 04 '16 at 12:41

1 Answers1

0

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]]
codester
  • 36,891
  • 10
  • 74
  • 72