2017-04-04 214 views
-4

我需要做解析此JSON字符串,需要进去iPhone中的所有值一样宽,URL等,有什么建议在Swift 3中解析JSON?

[[ 
    { 
    "id" : "1ab66b240b5441a35f1c963c802ebc23", 
    "sizes" : { 
     "IPhone" : { 
     "width" : 288, 
     "actualHeight" : 288, 
     "sizeName" : "IPhone", 
     "url" : "abc1.jpg", 
     "actualWidth" : 288, 
     "height" : 360 
     }, 
     "IPhone2" : { 
     "width" : 164, 
     "actualHeight" : 164, 
     "sizeName" : "Large", 
     "url" : "https:abc.jpg", 
     "actualWidth" : 164, 
     "height" : 205 
     }, 
    } 
    } 
]] 

感谢

回答

0

阅读JSON是很容易的:

{}是字典,[]是数组,所以所有嵌套集合类型是字典:

为了方便声明一个类型别名:

typealias JSONDictionary = [String : Any] 

if let image = aObject["image"] as? JSONDictionary, 
    let sizes = image["sizes"] as? JSONDictionary, 
    let xLarge = sizes["XLarge"] as? JSONDictionary, 
    let url = xLarge["url"] as? String { 
     print(url) 
} 

PS:不要使用基于斯威夫特for循环丑陋C风格的指数,这是推荐的方式:

for aObject in arrJSON as! [JSONDictionary] { 

,并删除下一行let aObject = ....

+0

感谢您的回复 –

1

使用SwiftyJSON解析值,它工作正常。

SwiftyJSON可以很容易地处理Swift中的JSON数据。例如:

let json = JSON(data: dataFromNetworking) 
if let userName = json[0]["user"]["name"].string { 
    //Now you got your value 
}