Codable 使用:
typealias Codable = Decodable & Encodable
它其实另外两个Protocol的集合, Decodable 和 Encodable。
一个用作数据解析 另一个用作数据编码
Codable协议 更加方便地将数据转化为JSON或存入本地磁盘。
Codable 的简单实用:
JSON结构:
{
"name" : "张三"
“age”: 10
}
对象模型:
struct Student:Codable {
var name: String
var age: Int
}
解码:
使用JSONDecoder 少的代码 把json 转换为Student类型
let jsonData = jsonString.data(encoding: .utf8)!
let decoder = JSONDecoder()
let student = try! decoder.decode(Student.self, for: jsonData)
注意:示例里json数据的key 和 Student结构体的属性名是相同的。
编码:相反, 可以使用JSONEncoder 来把 Student 对象编写为json数据
let encoder = JSONEncoder()encoder.outputFormatting = .prettyPrintedlet data = try! encoder.encode(student) print(String(data:data,encoding: .utf8)!)
*** encoder.outputFormatting = .prettyPrinted 是为了让JSON数据输出的结构更可读。
适配键 :
JSON
{
"name": "张三",
"age": 10,
"residential_address":"广东省深圳市南山区xxx"}
Student
structStudent:Codable{ var name: String
var age: Int
var residentialAddress: String
enumCodingKeys:String,CodeingKey{ case name
case age
case residentialAddress = "residential_address" // 关联代码
}}
数组:
let decoder = JSONDecoder()let students = try decoder.decode([Student].self, from: data)
使用Codable协议,处理数组也很简单,只要Array<T>里的T是继承于Codable协议的,那么Array<T>也是可以根据Codable协议解编码的。
使用参考文档: https://www.edoou.com/articles/1567751253581201
网友评论