【问题标题】:Loop though a json file and fill in an array Swift循环一个 json 文件并填充一个数组 Swift
【发布时间】:2016-07-08 07:21:43
【问题描述】:

我正在尝试遍历 json 并将每个项目放入自己的数组中。我不知道如何通过 json 循环。虽然我已经成功地放置了一次 json 并填充了数组,但现在我需要将整个 json 放入受尊重的数组中。任何帮助将不胜感激

这是我得到的:

func parseCoupons(response : String)
{
    print("Starting to parse the file")
    let data = response.dataUsingEncoding(NSUTF8StringEncoding)
    var myJson : NSArray
    myJson = []

    do {
        myJson = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
    }
    catch {
        print("Error")
    }

    for item in myJson.count {
        titleArray.append((myJson[item]as! NSDictionary)["name"] as! String)
        descriptionArray.append((myJson[item]as! NSDictionary)["description"] as! String)
        amountArray.append((myJson[item]as! NSDictionary)["amount"] as! Int)
        typeArray.append((myJson[item]as! NSDictionary)["type"] as! String)
        startDateArray.append((myJson[item]as! NSDictionary)["start_date"] as! String)
        endDateArray.append((myJson[item]as! NSDictionary)["end_date"] as! String)
        barcodeArray.append((myJson[item]as! NSDictionary)["barcode"] as! String)
    }

而我要解析的Json会是这个样子

[
 {
  "name": "Coupon Title",
  "description": "The Coupon Description",
  "type": "PERCENT_OFF",
  "amount": 15,
  "barcode": "4948473",
  "start_date": "2016-12-01",
  "end_date": "2016-12-25",

 },

ECT ECT ECT

]

【问题讨论】:

    标签: ios arrays json swift


    【解决方案1】:

    Swift 是一种面向对象的语言,所以创建一个自定义对象而不是使用一堆不相关的数组。

    struct Coupon {
    
      var name : String
      var description : String
      var amount : Int
      var type : String
      var startDate : String
      var endDate : String
      var barcode : String
    
    }
    

    parseCoupons使用Swift原生集合类型时,该方法返回解析后的Coupon项:

    func parseCoupons(response : String) -> [Coupon]
    {
      print("Starting to parse the file")
      let data = Data(response.utf8)
      var coupons = [Coupon]()
    
      do {
        let myJson = try JSONSerialization.jsonObject(with: data) as! [[String:Any]]
    
        for item in myJson {
          let name = item["name"] as! String
          let description = item["description"] as! String
          let amount = item["amount"] as! Int
          let type = item["type"] as! String
          let startDate = item["start_date"] as! String
          let endDate = item ["end_date"] as! String
          let barcode = item["barcode"] as! String
          let coupon = Coupon(name: name,
                              description: description,
                              amount: amount,
                              type: type,
                              startDate: startDate,
                              endDate: endDate,
                              barcode: barcode)
          coupons.append(coupon)
        }
      } catch {
        print("Error", error)
      }
      return coupons
    }
    

    旁注:您的do - catch 块毫无意义,good 代码必须在do 范围内,并且在重复循环中一次又一次地执行表达式myJson[item]as! NSDictionary) 效率非常低。

    编辑

    在 Swift 4 中,它变得更加方便。

    采纳Decodable

    struct Coupon : Decodable { ...
    

    并享受协议的魔力

    func parseCoupons(response : String) throws -> [Coupon]
    {
      print("Starting to parse the file")
      let data = Data(response.utf8)
    
      let decoder = JSONDecoder()
      decoder.keyDecodingStrategy = .convertFromSnakeCase
      return try decoder.decode([Coupon].self, from: data)
    }
    

    【讨论】:

      【解决方案2】:

      而不是像这样创建多个 array 创建包含 Dictionary 的对象。

      var arr : [NSDictionary] = [NSDictionary]()
      

      现在像这样在这个数组中添加你的所有对象

      for item in myJson.count {
          arr.append(myJson[item] as! NSDictionary)
      }
      

      现在你可以像这样使用这个数组的字典来访问每个元素

      print((arr[0] as! NSDictionary)["name"] as! String)
      

      希望这会对你有所帮助。

      【讨论】:

      • 这很好,但不完全是我需要的。我希望单独的数组将每个变量的数据分开,并且稍后我还将在代码的后面循环遍历每个数组。将它们分开有助于我保持它们的直线
      【解决方案3】:

      我通过调整和使用它工作的代码让它工作。 for 循环结构非常重要,否则它将无法正常工作。

          for i in 0..<myJson.count
          {
              titleArray.append((myJson[i]as! NSDictionary)["name"] as! String)
              descriptionArray.append((myJson[i]as! NSDictionary)["description"] as! String)
              amountArray.append((myJson[i]as! NSDictionary)["amount"] as! Int)
              typeArray.append((myJson[i]as! NSDictionary)["type"] as! String)
              startDateArray.append((myJson[i]as! NSDictionary)["start_date"] as! String)
              endDateArray.append((myJson[i]as! NSDictionary)["end_date"] as! String)
              barcodeArray.append((myJson[i]as! NSDictionary)["barcode"] as! String)
          }
      

      它与您的@Nirav 非常相似,所以感谢您引导我完成此操作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 2016-01-27
        • 2022-01-23
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        相关资源
        最近更新 更多