本文介绍了如何在swift4中解析对象内部的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用tableview解析JSON数据.在tableview中成功解析了tableview中的数据,但问题是用户单击tableview单元格以传递到详细信息ViewController.但是问题是我无法在
I'M using tableview to parsing JSON data. the parse data in tableview in successful parsed on my tableView but the problem is users click the tableview cell to pass to details ViewController.But the problem is i can't parse JSON in details ViewController in
这是我的JSON外观
[ { "id": "263", "userId": "2692" } ]这是我的代码
guard let url = URL(string: URL API) else { return } var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("Bearer \(AccessToken!)", forHTTPHeaderField: "Authorization") request.httpMethod = "GET" let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in do { let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [string: anyobject] print(json) label.text = json["id"] as? string }catch { } }.resume()推荐答案
使用Codable协议在swift4中解析json. 像这样声明您的模型:
Parse json in swift4 using Codable protocol. declare your model like this:
struct Model: Codable { let id: Double let userId: Double enum CodingKeys : String, CodingKey { case id = "id" case userId = "userId" } }然后,在获取数据后,使用此:
then, after getting data, use this:
do { let arrayValue = try JSONDecoder().decode([Model], from: data) } catch { }请注意,您的json是数组而不是字典!
Note that your json is array not dictionary!
更多推荐
如何在swift4中解析对象内部的JSON数组
发布评论