gpt4 book ai didi

json - 展开 Json Swift(发现为零)

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:25 24 4
gpt4 key购买 nike

我目前正在尝试在 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"
}
]
}
]

我想为“图片”行获取“名称”的值,但出现错误“在展开值时意外发现 nil”。

对于其他值,我以这种方式进行:

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

谢谢你的帮助!

最佳答案

图片不在您的其他值所在的子词典中。这应该可行,但在强制转换之前,您应该检查所有值是否为 nil。

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

关于json - 展开 Json Swift(发现为零),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30820019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com