Swift5中关于使用协议Codable将结构体转模型

2021-12-14  本文已影响0人  Johnson_9d92

Swift5中关于使用协议Codable将结构体转模型

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()
上一篇 下一篇

猜你喜欢

热点阅读