2017-09-26 105 views
-1

我有一个json,它有一个字典数组。我通过数组迭代从json像这样得到的元素...在Swift中迭代数组的问题

let prodId = prodArray.first?["product_id"] as? String 

这给了我product_id第一索引。但我的数组有10个元素。所以我正在使用for循环,如果我想要像数组一样获取数组中的所有id,而不是像第一个元素那样,我该怎么做?..?

编辑:此外,这是我json响应...

{ 
    "success": 1, 
    "TotalRevenue": “123.12 K", 
    "Productdata": [ 
     { 
      "product_id": "5", 
      "product_name": “abc” 
      "product_images": [ 
       { 
        "id": "938", 
        "image": "http://myApp.direct.com/public165_1_image_15", 
        "is_default": "1" 
       }, 
       { 
        "id": "939", 
        "image": "http://myApp.direct.com/public165_1_image_16", 
        "is_default": "0" 
       } 

      ] 
     } 
+0

我已经试过像这样... let prodId = product [“product_id”] as?字符串,但它会引发错误无法用类型为'String'的索引来下标'[[String:Any]]'的值' –

+0

您能否发布json解析代码? –

+0

@ User.bw该消息表明'product'包含一个字典数组,而不是一个字典。 – Paulw11

回答

0

可能,最好的,最简单的办法是使用flapMap

let productIds: [String] = prodArray.flapMap({ $0["product_id"] as? String }) 

flatMap允许您通过迭代阵列和尝试以获得product_id值(所以,如果没有值为$0["product_id"] as? StringflatMap过滤掉)。

UPD。

let jsonDict = // json, that converted into dictionary 

if let projectData = jsonDict["Productdata"] as? [[String: Any]] { 
    let productIds = projectData.flatMap({ $0["product_id"] as? String }) 
    let images = projectData.flatMap({ $0["product_images"] as? [[String: Any]] }).flatMap({ $0 }) 
    let imageIds = images.flatMap({ $0["id"] as? String }) 

    let imageURLs: [URL] = images.flatMap { image in 
     guard let imageURL = image["image"] as? String, let url = URL(string: imageURL) else { return nil } 
     return url 
    } 

    print(productIds) // ["5"] 
    print(imageIds) // ["938", "939"] 
    print(imageURLs) // [http://myApp.direct.com/public165_1_image_15, http://myApp.direct.com/public165_1_image_16] 
} 

此外,您可以try it online

+0

@安抚...我已经做了上面的编辑......根据你的建议,我试图让prodId为let productIds:[String] = prodArray.flatMap({$ 0 [“product_id”] as?String})以及进一步的image数组像这样... let prodImgArray:[String] = prodArray.flatMap({$ 0 [“product_images”] as?String})。这两个工作正常。但问题是,当试图得到这样的id ...让id:[String] = prodImgArray.flatMap({$ 0 [“id”] as?String})然后它会抛出错误'不能下标类型的值'String'与'String'类型的索引'...任何建议...? –

+0

@ User.bw,更新了我的答案 – pacification

+1

谢谢@pacification ... –

0

请尝试以下代码。

if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] { 

      if let productArray = jsonObj["Productdata"] as? [[String:Any]]{ 
       for product in productArray{ 

        if let prodId = prodArray.first?["product_id"] as? String { 
       } 

      } 
     } 
    }