展开Json Swift(找到零)

时间:2015-06-13 14:53:17

标签: json string swift nsdictionary

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

这就是我得到的:

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

我希望获得“图片”行的“名称”值,但我有错误“在展开值时意外发现零”。

对于其他值,我这样做:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

图片不在您的其他值的子字典中。这应该有效,但是在你强制施放之前你应该检查所有值是否为零。

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包含两个子词典,一个没有键,一个带有键'图片'。图片是一个包含一个子词典的数组。

相关问题