Swift5中关于使用协议Codable将结构体转模型
- 第一种情况,属性和服务器返回的字段一样情况下。
我们使用playground操场 来创建一个工程项目。今天我们不使用服务器返回json字符串来模拟。
import UIKit
let res1 = """
{
"name": "Jone",
"age": 17
}
"""
let data1 = res1.data(using: .utf8)!
debugPrint(data1)
struct Student: Codable {
let name: String
let age: Int
};
let decoder1 = JSONDecoder()
let strt1 = try! decoder1.decode(Student.self, from: data1)
debugPrint(strt1)
let encoder1 = JSONEncoder()
encoder1.outputFormatting = .prettyPrinted
let data3 = try! encoder1.encode(strt1)
debugPrint(String(data: data3, encoding: .utf8)!)
- 第二种情况,属性和服务器返回的字段个别不一样情况下。
let res2 = """
{
"name": "Jone",
"age": 17,
"born_in": "China"
}
"""
let data2 = res2.data(using: .utf8)!
struct Student2: Codable {
let name: String
let age: Int
let bornIn: String
enum CodingKeys: String,CodingKey {
case name
case age
case bornIn = "born_in"
}
}
let decoder2 = JSONDecoder()
let stu2 = try! decoder2.decode(Student2.self, from: data2)
debugPrint(stu2)
let encoder2 = JSONEncoder()
网友评论