Swift 3 json parsing

前端 未结 2 1801
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 08:51

I am running into troubles updating my app as Alamofire and SwiftyJSON are not yet supporting Swift 3. I have a url that would return me json as follows:

{
          


        
相关标签:
2条回答
  • 2021-01-16 09:23

    To loop over all of the products you need to extract and cast it to the correct type. In this case an array of [String: Any].

    I extracted the relevant bit of code and cleaned it up a bit to make this answer more readable.

    guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any],
        let products = json["products"] as? [[String: Any]]
        else { return }
    
    for product in products {
        guard let id = product["id"] as? Int,
            let options = product["options"] as? [[String: Any]]
            else { return }
    
        print(id)
        print(options)
    }
    
    0 讨论(0)
  • 2021-01-16 09:50

    This parses the JSON, the root object is a dictionary, the objects for products and options are arrays. One value respectively is printed as an example.

    if let jsonObject = try JSONSerialization.jsonObject(with:data, options: []) as? [String:Any] {
      print(jsonObject)
      if let products = jsonObject["products"] as? [[String:Any]] {
        for aProduct in products {
          print(aProduct["created_at"])
          if let options = aProduct["options"] as? [[String:Any]] {
            for option in options {
              print(option["product_id"])
            }
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题