codable swift_使用Codable进行Swift JSON解析

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? String
        self.age = aDecoder.decodeObject(forKey: "age") as? Int
    }

    init(name:String,age:Int) {
        self.name = name
        self.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 A
    case B
    case C
}
class Student: NSObject, Codable
{
    var name: String = ""
    var id: URL? = nil
    var year: Int = 0
    var isNew:Bool = true
    var peer: [String:String]? = nil
    var section: Section = .A

}

let student = Student()
student.name = "Anupam"
student.year = 2011
student.id = URL(string: "https://www.journaldev.com")
student.section = .B

let 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 A
    case B
    case C
}
class Student: NSObject, Codable
{
    var name: String = ""
    var id: URL? = nil
    var year: Int = 0
    var isNew:Bool = true
    var peer: [String:String]? = nil
    var section: Section = .A
    
    enum CodingKeys:String,CodingKey
    {
        case name
        case 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 A
    case B
    case C
}
class Student: NSObject, Codable
{
    var name: String = ""
    var id: URL? = nil
    var year: Int = 0
    var isNew:Bool = true
    var peer: [String:String]? = nil
    var section: Section = .A
    
    enum CodingKeys: String, CodingKey {
        case name = "user_name"
        case id = "user_id"
        case year
        case isNew = "is_new"
        case peer
        case 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值