通过Swift中的JSON数组循环

时间:2017-12-14 12:45:58

标签: json swift

我正在尝试遍历我从HTTP请求获取的JSON数组,但我不确定如何。

我试过的是:

var request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: Double.infinity)
if Reachability.isConnectedToNetwork(){
    request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: Double.infinity);
}
let session = URLSession.shared
var getResp = false

var zinnen : [Zin] = []
let task = session.dataTask(with: request as URLRequest,
                            completionHandler: { data, response, error -> Void in
                                let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
                                for case let data in json {
                                    if let zin = Zin(json: data) {
                                        zinnen.append(zin)
                                    }
                                }
})
task.resume()

这是我的结构:

struct Zin : CustomStringConvertible {
    var description: String

    let id : Int
    let dutch_sentence : String
    let polish_sentence : String
    init(dictionary: [String: Any]) {
        self.id = dictionary["id"] as? Int ?? 0
        self.dutch_sentence = dictionary["dutch_sentence"] as? String ?? ""
        self.polish_sentence = dictionary["polish_sentence"] as? String ?? ""
    }
}

JSON数组的示例:

[  
   {  
      "id":"35",
      "dutch_sentence":"Ja",
      "polish_sentence":"Tak"
   },
   {  
      "id":"36",
      "dutch_sentence":"Nee",
      "polish_sentence":"Nie"
   }
]

但在此我得到了错误

  

输入'[String:Any] ??'不符合协议'序列'

1 个答案:

答案 0 :(得分:1)

不要忽略错误! try?和可选的向下转换都会导致嵌套的可选(Optional<Optional<[String:Any]>>),当然这不是一个序列,即使是在转换为数组时也是如此。

处理错误,可选绑定结果并将结果转换为指定的数组 [[String:String]]。根据JSON,id的值为String而不是Int

do {
   if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
      for zinData in json {
          let zin = Zin(dictionary: zinData)
          zinnen.append(zin)
      }
   }
} catch { print(error) }

PS:Zin类中的初始化程序与解析代码中的初始化程序不匹配。我正在使用该类的版本。您必须将id的类型从Int更改为String