使用Swift从JSON中提取数组

使用Swift从JSON中提取数组

问题描述:

Java经验的负载,但与Swift相关的n00b。我有以下的JSON,我从中没有提取“图像”阵列,这可能有多达3图像...使用Swift从JSON中提取数组

{ 
     "status" : "OPEN", 
     "description" : “…”, 
     "name" : “…”, 
     "owner" : 1, 
     "images" : [ 
     { 
      "id" : 1, 
      "path" : "\/uploads\/1-60003456.jpeg" 
     } 
     ], 
     "created" : 1459135829000, 
     "id" : 1 
    } 

我一直运行到的编译时和运行时主机错误。例如,从SwiftyJSON文档验证码:

for (key,subJson):(String, JSON) in json { 
    if(key == "images"){ 
     let myImages = subJson.array 
     print(myImages![0]["path"]) 
    } 
} 

正确打印出来的价值“路径”,还试图保存在我的[字符串]的图像,值:

images.append(myImages![0]["path"] as String) 

给出错误“不能用类型为String的索引来标记JSON类型的值“

XCode告诉我subJson是”图像“(或者它是一个字典数组吗?)的NSDictionary,但是当我尝试将它转换为,我得到“无法将JSON类型的值转换为在coersion中键入NSDictionary”。

我确定这是一个简单的语法错误,但在这一点上,我只是在各种错误之间来回移动。感谢您的任何指导。

不要使用向下转换,SwiftyJSON已经完成了这项工作。 SwiftyJSON有对象的字符串表示一个可选的getter它已经被解析:

myImages![0]["path"].string 

因为它是一个可选要安全地解开它:

if let path = myImages![0]["path"].string { 
    images.append(path) 
} 

如果myImages![0]["path"]不是一个字符串,那么SwiftyJSON为您提供尽可能多的可选干将,因为有JSON类型:

myImages![0]["path"].array 
myImages![0]["path"].dictionary 
myImages![0]["path"].int 

随着SwiftyJSON你也可以直接下标:

if let firstImagePath = json["images"][0]["path"].string { 
    // use "firstImagePath" 
} 

最后,另一种循环:

if let images = json["images"] { 
    for image in images { 
     if let path = image["path"].string { 
      // use "path" 
     } 
    } 
} 
+0

完美。谢谢,埃里克。 – MolonLabe

+0

不客气。 – Moritz