Swift-JSON Encode && Decode

typealias Codable = Encodable & Decodable

struct Employee: Codable {
    var name:String
    var id: Int
    var mToy:Toy
}

struct Toy:Codable {
    var name:String
}

extension Employee:CustomStringConvertible {
    var description: String {
        return name + "(" + String(id) + "): " + mToy.name
    }
}



        /// encode instance to jsonString
        let toyA = Toy(name: "Teddy Bear")
        let employeeA = Employee(name: "EmployA", id:1, mToy:toyA)
        let jsonEncoder = JSONEncoder()
        let jsonData = try? jsonEncoder.encode(employeeA)
        // Xcode omits jsonData and only provides the number of bytes in jsonData
        // jsonData contains an unreadable representation of employeeA
        print("jsonData: \(jsonData)")
        let jsonString = String(data: jsonData!, encoding: .utf8)
        print("jsonString: \(jsonString)")
        
        
        /// decode jsonString to instance
        let jsonDecoder = JSONDecoder()
        let employeeADecoded = try? jsonDecoder.decode(Employee.self, from: jsonData!)
        print(employeeADecoded!)


//result
/*

  jsonData: Optional(54 bytes)

  jsonString: Optional("{\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}")

  EmployA(1): Teddy Bear

*/

 

假设,现在后台改接口了

from : {\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}

to : {\"name\":\"EmployA\",\"gift\":\"Teddy Bear\",\"emplyeeID\":1}

 

需要实现encoding 和 decoding的逻辑。

encode 需要实现 encode(to: Encoder) throws

decode 需要实现 init(from decoder: Decoder) throws

//typealias Codable = Encodable & Decodable

struct Employee{
    var name:String
    var id: Int
    var mToy:Toy
    
    enum CodingKeys: String, CodingKey{
        case id = "emplyeeID"
        case name
        case gift
    }
}

extension Employee: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(id, forKey: .id)
        try container.encode(mToy.name, forKey: .gift)
    }
}

extension Employee:Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        id = try values.decode(Int.self, forKey: .id)
        let gift = try values.decode(String.self, forKey: .gift)
        mToy = Toy(name: gift)
    }
}

extension Employee:CustomStringConvertible {
    var description: String {
        return name + "(" + String(id) + "): " + mToy.name
    }
}

struct Toy{
    var name:String
}

 

转载于:https://www.cnblogs.com/HackHer/p/8507888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值