解开Json Swift(发现nil) [英] Unwrapping Json Swift (found nil)

查看:97
本文介绍了解开Json Swift(发现nil)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试用Xcode解码Json,但我没有成功获得其中之一.

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

这就是我得到的:

[
  {
     "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"
         }
        ]
  }
]

我想为"Pictures"行获取"name"的值,但出现错误在解包值时意外发现nil".

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

谢谢您的帮助!

推荐答案

图片不在您的其他值所在的子词典中.这应该可以,但是在强制强制使用所有值之前,您应该检查所有值是否为零.

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包含两个子词典,一个不带键,另一个带键图片".图片是一个包含一个小词典的数组.

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

这篇关于解开Json Swift(发现nil)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆