Swift中的Array中的对象

时间:2018-09-17 17:08:47

标签: ios json swift parsing

有人可以帮助解析这种JSON对象吗?

{  
   "array":[  
      {  
         "title":"",
         "desc":""
      },
      {  
         "title":"",
         "desc":""
      },
      {  
         "title":"",
         "desc":""
      }
   ]
}

我的代码不起作用

let task = self.session.dataTask(with: url) {
        data, response, error in
        if let data = data,
            let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            for case let announcment in json!["array"]{
                guard let title = announcment["title"] as? String,
                    let description = announcment["desc"] as? String,
                else{ return }
    }
    task.resume()

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

漂亮地打印JSON使操作变得更容易:

{
   "array":[
      {
         "title":"",
         "desc":""
      },
      {
         "title":"",
         "desc":""
      },
      {
         "title":"",
         "desc":""
      }
   ]
}

您需要先获取阵列。字典数组的类型为[[String: Any]]

let task = self.session.dataTask(with: url) {
    data, response, error in
    if let data = data,
        let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            guard let announcements = json["array"] as? [[String: Any]] 
                else { return }

            announcements.forEach { announcement in
            guard let title = announcement["title"] as? String,
                let description = announcement["desc"] as? String
                else { return }
            // Do something with the result
            }
       }
  }
task.resume()

答案 1 :(得分:1)

您可以构建数据并将其编码:

struct Root: Codable {
    let array: [Announcement]
}
struct Announcement: Codable {
    let title: String
    let desc: String
}

let data = Data("""
{"array":[{"title":"","desc":""},{"title":"","desc":""},{"title":"","desc":""}]}
""".utf8)

do {
    let announcements = try JSONDecoder().decode(Root.self, from: data).array
    for announcement in announcements {
        print(announcement)
    }
} catch {
    print(error)
}

这将打印

Announcement(title: "", desc: "")
Announcement(title: "", desc: "")
Announcement(title: "", desc: "")