Swift Archiving序列化

卢英范
2023-12-01

Swift采用新的序列化方式,Codable
Foundation会实现这两种方法(Decodable & Encodable),你不需要做任何事情
而且可以从模型中自定义JSON中的key,非常方便

struct Engine: Codable {
    var factoryName = "factoryName"
    
    // 修改json中的key名称
    private enum CodingKeys: String, CodingKey {
        case factoryName = "factory_name"
    }
}

struct Car: Codable {
    var brand = "宝马"
    var wheelsNumber = ["1", "2", "3", "4"]
    var engine = Engine()
    
    // 修改key的名称,若json中不需wheelsNumber字段时,不写case
    private enum CodingKeys: String, CodingKey {
        case brand = "brand_name"
        case engine
        // case wheelsNumber
    }
}

序列化

    let car = Car()
    let data: Data? = try? JSONEncoder().encode(car)
    print(String(data: data!, encoding: .utf8)!)

输出:{“brand_name”:“宝马”,“engine”:{“factory_name”:“factoryName”}}

反序列化

    if let car = try? JSONDecoder().decode(Car.self, from:data!) {
        print(car)
    }

输出:Car(brand: “宝马”, wheelsNumber: [“1”, “2”, “3”, “4”], engine: Memorize.Engine(factoryName: “factoryName”))

 类似资料: