swift常用第三方庫,codable swift_使用Codable進行Swift JSON解析

 2023-11-19 阅读 24 评论 0

摘要:codable swiftIn 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. 在本教程中,我們將討論可編碼協議

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)

swift常用第三方庫,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)

swift編譯器、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:

swift codable cusom keys 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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/183256.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息