Unwrapping Json Swift (found nil)

北城以北 提交于 2020-01-15 12:15:33

问题


i currently trying to decode Json in Xcode, but i not succed to get one of them.

This is what i get :

[
  {
     "id": "1",
     "title": "bmw",
     "price": "500.00",
     "description": "330",
     "addedDate": "2015-05-18 00:00:00",
     "user_id": "1",
     "user_name": "CANOVAS",
     "user_zipCode": "32767",
     "category_id": "1",
     "category_label": "VEHICULES",
     "subcategory_id": "2",
     "subcategory_label": "Motos",
     "bdd": {} 
  }
     "pictures": 
        [
         { "name": "http://cars.axlegeeks.com/sites/default/files/4315/media/images/2014_BMW_Z4_sDrive28i_3790993.jpg"
         }
        ]
  }
]

And i want to get the value of "name" for the "Pictures" lines but i have the error "unexpectedly found nil while unwrapping value".

For the others values i proceed this way :

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary

            //Browse into JSON to get datas
            let resp = jsonData["0"] as! NSDictionary
                let user_nameR = resp["user_name"] as! String
                let user_zipCodeR = resp["user_zipCode"] as! String
                let titleR = resp["title"] as! String
                let priceR = resp["price"] as! String
                let descriptionR = resp["description"] as! String

Thank's for your help !


回答1:


Pictures is in not in the subdictionary your other values are. This should work, but you should check all values if they are nil before you force cast them.

if let pictureArray = jsonData["pictures"] as? NSArray
{
    if let pictureDict = pictureArray.firstObject as? NSDictionary
    {
        if let pictureName = pictureDict.objectForKey("name") as? String
        {
            NSLog("Picture name: %@", pictureName)
        }
    }
}

jsonData contains two sub-dictionaries, one without a key and one with key 'pictures'. Pictures is an array containing one sub-dictionary.



来源:https://stackoverflow.com/questions/30820019/unwrapping-json-swift-found-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!