如何在swift4中解析对象内部的JSON数组

编程入门 行业动态 更新时间:2024-10-03 17:17:32
本文介绍了如何在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数组

本文发布于:2023-11-26 09:46:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   如何在   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!