codable swift

In this tutorial, we’ll be discussing the Codable Protocol and its forms in order to parse/serialize JSON in our Swift Playground. We have previously discussed Swift JSON parsing using JSONSerialization.

在本教程中,我们将讨论可编码协议及其形式,以便在我们的Swift Playground中解析/序列化JSON。 前面我们已经讨论了使用JSONSerialization Swift JSON解析 。

快速编码协议 (Swift Codable Protocol)

Codable Protocol was introduced in Swift4 and is a nice replacement for NSCoding.

Swift4中引入了可编码协议,它很好地替代了NSCoding。

Let’s review NSCoding once.

让我们回顾一下NSCoding。

Swift NSCoding (Swift NSCoding)

NSCoding protocol which is a part of the foundation framework has been there for the same purpose i.e. encoding and decoding data to/from JSON respectively.

NSCoding协议是基础框架的一部分,出于相同的目的而存在,即分别向JSON编码数据和从JSON编码数据。

Let’s use NSCoding in our XCode Playground.

让我们在XCode Playground中使用NSCoding。

class Student : NSObject, NSCoding
{var name: String?var age: Int?required init?(coder aDecoder: NSCoder){//Returns an object initialized from data in a provided unarchiver.self.name = aDecoder.decodeObject(forKey: "name") as? Stringself.age = aDecoder.decodeObject(forKey: "age") as? Int}init(name:String,age:Int) {self.name = nameself.age = age}func encode(with aCoder: NSCoder){//Encodes the given object using provided archiver.aCoder.encode(self.name, forKey: "name")aCoder.encode(self.age, forKey: "age")}override var description: String {get {return "[ name=\(self.name) ; age=\(self.age) ]"}}
}

encode along with the decoder init function must be implemented since we’ve used the NSCoding Protocol.

由于我们使用了NSCoding协议,因此必须与encode器初始化函数一起实现encode

For serialization we use the class NSKeyedArchiver:

对于序列化,我们使用类NSKeyedArchiver:

let student = Student(name: "Anupam", age: 24)
let data = NSKeyedArchiver.archivedData(withRootObject: student)
let decoded = NSKeyedUnarchiver.unarchiveObject(with: data) as! Student
print(decoded)//Prints [ name=Optional("Anupam") ; age=Optional(24) ]

Try changing the key name in any of the function and you’ll see a nil returned.

尝试在任何函数中更改键名,您将看到nil返回。

NSCoding is useful for saving the application state by saving the object graph in the Archiver.

NSCoding对于通过将对象图保存在Archiver中来保存应用程序状态非常有用。

Having said that, NSCoding has its disadvantages too:

话虽如此,NSCoding也有其缺点:

  • Cannot be used with anything else except Classes in Swift.除Swift中的类外,不能与其他任何东西一起使用。
  • Too much redundant code for encoding and decoding. Need to add for each field.编码和解码的冗余代码过多。 需要为每个字段添加。

Apple recognized these drawbacks and brought in the Codable Protocol for swifter development!

Apple意识到了这些缺点,并引入了Codable协议以加快开发速度!

Codable Protocol is the amalgamation of two protocols: encodable and decodable.

可编码协议是两种协议的组合: encodabledecodable

Codable is a typealias:

Codable是一种类型别名:

typealias Codable = Encodable & Decodable

These protocols work with the Swift class, struct, enums.

这些协议与Swift类 struct 枚举一起使用 。

Another protocol CodingKey is used to defined our own custom keys.

另一个协议CodingKey用于定义我们自己的自定义密钥。

We can omit certain values by assigning default values to them.

我们可以通过为它们分配默认值来省略某些值。

Encodable protocol encodes the custom type into a data. The data can be a plist or a JSON.

可编码协议将自定义类型编码为数据。 数据可以是plist或JSON。

Encodable uses the encode(to: ) function.

Encodable使用encode(to: ) :)函数。

Decodable coverts the data back to the custom type.

可解码将数据转换回自定义类型。

Decodable uses the init(from: ) function.

Decodable使用init(from: ) :)函数。

JSONEncoder and JSONDecoder are used for JSON data

JSONEncoderJSONDecoder用于JSON数据

PropertyListEncoder and PropertyListDecoder are used for plist data.

PropertyListEncoderPropertyListDecoder用于plist数据。

编码和解码JSON数据 (Encoding and Decoding JSON Data)

enum Section: String, Codable
{case Acase Bcase C
}
class Student: NSObject, Codable
{var name: String = ""var id: URL? = nilvar year: Int = 0var isNew:Bool = truevar peer: [String:String]? = nilvar section: Section = .A}let student = Student()
student.name = "Anupam"
student.year = 2011
student.id = URL(string: "https://www.journaldev.com")
student.section = .Blet encodedObject = try? JSONEncoder().encode(student)
if let encodedObjectJsonString = String(data: encodedObject!, encoding: .utf8)
{print(encodedObjectJsonString)
}

To Decode a JSON string we do:

要解码JSON字符串,请执行以下操作:

let jsonString = """
{
"name":"Anupam",
"isNew":true,
"year":2018,
"id":"j.com",
"section":"A"
}
"""
if let jsonData = jsonString.data(using: .utf8)
{let studentObject = try? JSONDecoder().decode(Student.self, from: jsonData)
}

Decoding a JSON Array

解码JSON数组

let jsonString = """
[{
"name":"Anupam",
"isNew":true,
"year":2018,
"id":"j.com",
"section":"A"
},
{
"name":"Anupam",
"isNew":true,
"year":2011,
"id":"j.com",
"section":"C"
}]
"""
if let jsonData = jsonString.data(using: .utf8)
{let studentObject = try? JSONDecoder().decode([Student].self, from: jsonData)print(studentObject?.count)
}
If the json string that is passed to the decoder doesn’t have all the properties, it will return a nil instance.
如果传递给解码器的json字符串不具有所有属性,则它将返回nil实例。

Nested Data

嵌套数据

删除不必要的属性 (Removing unnecessary properties)

Using the CodingKey protocol we can decide which properties we want to encode or decode.

使用CodingKey协议,我们可以决定要编码或解码的属性。

enum Section: String, Codable
{case Acase Bcase C
}
class Student: NSObject, Codable
{var name: String = ""var id: URL? = nilvar year: Int = 0var isNew:Bool = truevar peer: [String:String]? = nilvar section: Section = .Aenum CodingKeys:String,CodingKey{case namecase id}
}let student = Student()
student.name = "Anupam"
student.year = 2011
student.id = URL(string: "https://www.journaldev.com")
student.section = .B

Output:

输出:

{"name":"Anupam","id":"https:\/\/www.journaldev.com"}

Only the cases passed are encoded.

只有通过的案例才被编码。

使用自定义键名 (Using custom key names)

Again the CodingKey protocol is used to assign custom key names to the properties that will be encoded and decoded.

同样,使用CodingKey协议将自定义密钥名称分配给将要编码和解码的属性。

enum Section: String, Codable
{case Acase Bcase C
}
class Student: NSObject, Codable
{var name: String = ""var id: URL? = nilvar year: Int = 0var isNew:Bool = truevar peer: [String:String]? = nilvar section: Section = .Aenum CodingKeys: String, CodingKey {case name = "user_name"case id = "user_id"case yearcase isNew = "is_new"case peercase section}
}

Output:

输出:

This brings an end to this tutorial on Swift Codable Protocol. It’s used often in JSON Parsing in iOS Applications.

这样就结束了有关Swift Codable Protocol的本教程。 它经常在iOS应用程序的JSON解析中使用。

翻译自: https://www.journaldev.com/21850/swift-json-parsing-codable

codable swift

codable swift_使用Codable进行Swift JSON解析相关推荐

  1. iOS Swift JSON解析教程

    In this tutorial, we will learn how to parse a JSON response in our iOS Application using Swift. We ...

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

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

  3. Swift JSON 教程:使用 JSON

    原文:Swift JSON Tutorial: Working with JSON 作者:Luke Parham 译者:kmyhy 2017-1-15 更新说明:本教程由 Luke Parham 更新 ...

  4. swift php json解析,Swift 4.0 | JSON数据的解析和编码

    文 / 菲拉兔 自己撸的图 要求: Platform: iOS8.0+ Language: Swift4.0 Editor: Xcode9 [问题补充2017-09-28] 最近我发现了一个问题:在S ...

  5. 【JSON解析】JSON解析

    前三篇博客分别介绍了xml的三种解析方法,分别是SAX,DOM,PULL解析XML,兴趣的朋友可以去看一下这[XML解析(一)]SAX解析XML,[XML解析(二)]DOM解析XML,[XML解析(三 ...

  6. Swift JSON与模型转换(HandyJSON封装)

    2018.05.02 20:20:16字数 1,493阅读 5,017 一 简介 二 特性 三 安装使用以及封装 四 使用示例 五 总结 一 简介 HandyJSON是一个用于Swift语言中的JSO ...

  7. android Json解析详解

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语 言的支持),从而可以在不同平台间进行数 ...

  8. json解析:[1]gson解析json

    客户端与服务器进行数据交互时,常常需要将数据在服务器端将数据转化成字符串并在客户端对json数据进行解析生成对象.但是用jsonObject和jsonArray解析相对麻烦.利用Gson和阿里的fas ...

  9. spring boot2 修改默认json解析器Jackson为fastjson

    fastjson是阿里出的,尽管近年fasjson爆出过几次严重漏洞,但是平心而论,fastjson的性能的确很有优势,尤其是大数据量时的性能优势,所以fastjson依然是我们的首选:spring ...

最新文章

  1. ASP.NET Aries 高级开发教程:Excel导入配置之规则说明(下)
  2. IP地址,子网掩码、默认网关,DNS理论解释
  3. qs.stringify和JSON.stringify的使用和区别
  4. 一个Excel导出类的实现过程(二):显示定制
  5. 【转】可编程管线基本流程
  6. java23中设计模式——行为模式——Memento(备忘机制)
  7. 一个例子带你搞懂python作用域中的global、nonlocal和local
  8. github 思维导图开元软件_Mymind教学系列--Github上的免费且强大思维导图工具-(一)...
  9. IBAction和IBOutlet
  10. ae图片无缝循环滚动_HTML图片滚动
  11. ARM64体系结构与编程之cache必修课(中)
  12. 基于STC89C52单片机的多功能智能清洁小车设计
  13. 别人的底鼓/808为什么比你有力?你可能忘了用这个插件
  14. 组合优化问题MATLAB程序,组合优化问题(一).ppt
  15. 你有必要不沾计算机一段时间英语,八年级上册英语第一单元背默(人教版)
  16. python猜字游戏
  17. 关于light7使用路由经验总结及踩的坑
  18. 【Java定时器】每天凌晨12点执行一次
  19. 产品:“嘘,这事千万别让开发知道”
  20. jnz和djnz_51单片机之系统指令

热门文章

  1. Opencv求多边形或轮廓的凸包(Hull)
  2. 在Apache中隐藏Php文件后缀
  3. 远程注入利用远程线程直接注入
  4. [转载] issubclass在python中的意思_python issubclass 和 isinstance函数
  5. [转载] Python字典及基本操作(超级详细)
  6. transient是干嘛的
  7. LeetCode447. Number of Boomerangs
  8. 自由缩放属性-resize(禁止textarea的自由缩放尺寸功能)
  9. SQL查询-巧用记录数统计人数
  10. C++静态成员总结(转)