In this tutorial, we will learn how to parse a JSON response in our iOS Application using Swift. We will display the parsed response in a UITableView. To know more about UITableView, check out this tutorial before proceeding ahead.

在本教程中,我们将学习如何使用Swift在我们的iOS应用程序中解析JSON响应。 我们将在UITableView中显示已解析的响应。 要了解有关UITableView的更多信息,请先阅读本教程,然后再继续。

Swift JSON解析 (Swift JSON Parsing)

JSON is the most commonly used format to send and receive data from the web services. The data is in the form of key-value pairs. Using Swift Dictionaries we can easily fetch the values from the keys.

JSON是最常用的从Web服务发送和接收数据的格式。 数据采用键值对的形式。 使用Swift字典,我们可以轻松地从键中获取值。

In this tutorial, we’ll be parsing JSON data from a local resource file.

在本教程中,我们将从本地资源文件中解析JSON数据。

The JSONSerialization class is used to parse a JSON data into a dictionary of key-value pairs by converting the Data object.

JSONSerialization类用于通过转换Data对象将JSON数据解析为键值对字典。

The type of a JSON data is [String: Any].

JSON数据的类型为[String: Any]

Let’s create a single view iOS Application in which we’ll parse the data from a locally created JSON file into the TableView.

让我们创建一个单视图iOS应用程序,在其中将本地创建的JSON文件中的数据解析为TableView。

iOS JSON解析示例项目结构 (iOS JSON Parsing Example Project Structure)

In the Main.storyboard we’ve added a label and a TableView to our ViewController.

在Main.storyboard中,我们向ViewController添加了标签和TableView。

We’ve set the TableView delegates to the ViewController.

我们已经将TableView委托设置为ViewController。

For more info on how to set up a TableView using Storyboard, refer this tutorial.

有关如何使用Storyboard设置TableView的更多信息,请参考本教程。

Swift JSON解析代码 (Swift JSON Parsing Code)

We will be parsing JSON data from the file. The response.json file looks like this:

我们将从文件中解析JSON数据。 response.json文件如下所示:

Serialising the data

序列化数据

let url = Bundle.main.url(forResource: "response", withExtension: "json")guard let jsonData = url else{return}
guard let data = try? Data(contentsOf: jsonData) else { return }
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else{return}

In the above code, we fetch the file over the Bundle.main.url instance.

在上面的代码中,我们通过Bundle.main.url实例获取文件。

The Data instance converts it into a Data format which is then serialized as JSON.

Data实例将其转换为Data格式,然后将其序列化为JSON。

Fetching data from the JSON instance

从JSON实例获取数据

Now that we’ve got the JSON instance, we can fetch the data in the following manner:

现在我们有了JSON实例,我们可以通过以下方式获取数据:

if let dictionary = json as? [String: Any] {if let title = dictionary["title"] as? String {labelHeader.text = title}if let year = dictionary["year"] as? Double {print("Year is \(year)")}if let more_info = dictionary["more_info"] as? Double {//This doesn't get printed.print("More_info is \(more_info)")}for (key, value) in dictionary {print("Key is: \(key) and value is \(value)" )}}

In the TableView, we’ll populate another JSON file :

在TableView中,我们将填充另一个JSON文件:

ViewController.swift

ViewController.swift

import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {@IBOutlet weak var labelHeader: UILabel!@IBOutlet weak var tableView: UITableView!var movieList = [MarvelData]()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.let url = Bundle.main.url(forResource: "response", withExtension: "json")guard let jsonData = urlelse{print("data not found")return}guard let data = try? Data(contentsOf: jsonData) else { return }guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else{return}if let dictionary = json as? [String: Any] {if let title = dictionary["title"] as? String {labelHeader.text = title}if let year = dictionary["year"] as? Double {print("Year is \(year)")}if let more_info = dictionary["more_info"] as? Double {//This doesn't get printed.print("More_info is \(more_info)")}for (key, value) in dictionary {print("Key is: \(key) and value is \(value)" )}}//Now lets populate our TableViewlet newUrl = Bundle.main.url(forResource: "marvel", withExtension: "json")guard let j = newUrlelse{print("data not found")return}guard let d = try? Data(contentsOf: j)else { print("failed")return}guard let rootJSON = try? JSONSerialization.jsonObject(with: d, options: [])else{ print("failedh")return}if let JSON = rootJSON as? [String: Any] {labelHeader.text = JSON["title"] as? Stringguard let jsonArray = JSON["movies"] as? [[String: Any]] else {return}print(jsonArray)let name = jsonArray[0]["name"] as? Stringprint(name ?? "NA")print(jsonArray.last!["year"] as? Int ?? 1970)for json in jsonArray{guard let movieName = json["name"] as? String else{ return }guard let movieYear = json["year"] as? Int else{ return }movieList.append(MarvelData(movieName: movieName, movieYear: movieYear))}self.tableView.reloadData()}}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return movieList.count}func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let currentMovie = movieList[indexPath.row]let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCellcell.textLabel?.text = currentMovie.movieNamecell.detailTextLabel?.text = "\(currentMovie.movieYear)"return cell}}struct MarvelData {let movieName: Stringlet movieYear: Intpublic init(movieName: String, movieYear: Int) {self.movieName = movieNameself.movieYear = movieYear}
}

In the above code, we’ve parsed the second json file as well and appended each of the JSON Array elements into the array which holds the structures.

在上面的代码中,我们还解析了第二个json文件,并将每个JSON Array元素追加到保存结构的数组中。

To display this data we must call reloadData() over the tableView instance.

要显示此数据,我们必须在tableView实例上调用reloadData()

We can make the code that sets the json values in the structure instances much better.

我们可以使在结构实例中设置json值的代码更好。

struct MarvelData {var movieName: Stringvar movieYear: Intinit(_ dictionary: [String: Any]) {self.movieName = dictionary["name"] as? String ?? "NA"self.movieYear = dictionary["year"] as? Int ?? 1970}
}

Doing this we can change our :

这样做我们可以更改:

guard let movieName = json["name"] as? String else{ return }
guard let movieYear = json["year"] as? Int else{ return }
movieList.append(MarvelData(movieName: movieName, movieYear: movieYear))

to

movieList.append(MarvelData(json))

Instead of iterating over the jsonArray using a for loop, we can easily use the handy operator concatMap in Swift. So this:

无需使用for循环遍历jsonArray,我们可以轻松地在Swift中使用方便的运算符concatMap。 所以这:

for json in jsonArray
{movieList.append(MarvelData(json))
}

Changes to

更改为

movieList = jsonArray.compactMap{return MarvelData($0)}
//or
movieList = jsonArray.compactMap{MarvelData($0)}
//or
movieList = jsonArray.compactMap(MarvelData.init)

This is the power of Swift!

这就是Swift的力量!

The output of the above application in action is:

上面应用程序的实际输出为:

This brings an end to this tutorial. You can download the project from the link below.

本教程到此结束。 您可以从下面的链接下载项目。

iOSJsonParsingiOSJson解析

翻译自: https://www.journaldev.com/21839/ios-swift-json-parsing-tutorial

iOS Swift JSON解析教程相关推荐

  1. codable swift_使用Codable进行Swift JSON解析

    codable swift In this tutorial, we'll be discussing the Codable Protocol and its forms in order to p ...

  2. 阿里json解析教程

    阿里json解析教程 第一步:引入阿里json解析工具jar包 第二步:见代码 { { "AppRequest":{ "name":"xiaomign ...

  3. HandyJSON的swift json解析第三方使用教程

    文章目录 安装方法 让模型遵守协议HandyJSON,嵌套模型的子模型也要继承HandyJSON 解析json数据 从json下一个子节点进行解析 解析数组 安装方法 podfile里面 pod 'H ...

  4. iOS开源JSON解析库MJExtension

    iOS中JSON与NSObject互转有两种方式:1.iOS自带类NSJSONSerialization 2.第三方开源库SBJSON.JSONKit.MJExtension.项目中一直用MJExte ...

  5. IOS中Json解析的四种方法

    2019独角兽企业重金招聘Python工程师标准>>> 作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式. 有的json代码格式比较混乱,可以使用此& ...

  6. 【转】IOS中Json解析的四种方法

    原文网址:http://blog.csdn.net/enuola/article/details/7903632 作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式. 有 ...

  7. ios json包含html,IOS中Json解析的四种方法

    发现自己有很多文档,所以现在整理一下,以防忘了... 作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式. 有的json代码格式比较混乱,可以使用此"http: ...

  8. iOS Swift GCD 开发教程

    本教程将带你详细了解 GCD 的概念和用法,通过文中的代码示例和附带的 Github 示例工程,可以进一步加深对这些概念的体会.附带的示例工程是一个完整可运行的 App 项目:DispatchQueu ...

  9. php json解析教程,php解析json

    本帖最后由 yskang 于 2012-08-08 10:07:31 编辑 这是某个软件在在线情况 远程获取的json数据,其中我需要records值,这个records:31就是在线总数,然后下面获 ...

最新文章

  1. 【计算机网络】网络安全 : 报文鉴别 ( 密码散列函数 | 报文摘要算法 MD5 | 安全散列算法 SHA-1 | MAC 报文鉴别码 )
  2. 若依前后端分离版怎样去掉登录验证码
  3. 《数据库SQL实战》查找薪水涨幅超过15次的员工号emp_no以及其对应的涨幅次数t
  4. ui边框设计图_UI设计形状和对象基础知识:填充和边框
  5. CakePHP你必须知道的21条技巧
  6. 脚本安装Rocky版OpenStack 1控制节点+1计算节点环境部署
  7. android实现字体滚动,Android实现字幕滚动的方法
  8. java核心技术卷一,二(经典)
  9. 怎样设定目标系列总结
  10. 如何解决5万的并发量
  11. 强网杯团队赛---Misc
  12. 个人计算机有ip地址吗,如何查看ip? 查看个人电脑IP地址五大方法
  13. android和苹果位置共享,苹果和安卓手机修改微信共享位置方法。
  14. python切片是什么意思_python切片的理解
  15. 10个降低PCB成本的技巧!PCB采购必须掌握!
  16. Android基础--首选项(SharedPreferences)
  17. Scala - 使用转义字符 \\ 与 | 分割字符
  18. 摩杜云亮相CDEC2021中国数字智能生态大会,始终专注云+数据
  19. 用html写一个简单课表
  20. 管理者的七大失败原因

热门文章

  1. Android ADV 虚拟卡常见错误Failed to push的解决
  2. 正则表达式 查找以某些字符开始 某些字符结束的匹配项 解决之道
  3. 基本的阿里云Linux服务器设置
  4. [转载] python中string函数的用法_python中string模块各属性以及函数的用法
  5. [转载] Java:简述Java中的自定义异常
  6. 阶段1 语言基础+高级_1-3-Java语言高级_04-集合_08 Map集合_3_Map接口中的常用方法...
  7. web自动化测试python+selenium学习总结----selenium安装、浏览器驱动下载
  8. BZOJ4471 : 随机数生成器Ⅱ
  9. git学习(三)分支管理
  10. mysql删除check约束_高级SQL特性——约束与索引