How do I use custom keys with Swift 4's Decodable protocol?

前端 未结 4 908
面向向阳花
面向向阳花 2020-11-22 14:57

Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this?

E.g., say I have a struct

<         


        
4条回答
  •  余生分开走
    2020-11-22 15:47

    By using CodingKey you can use custom keys in codable or decodable protocol.

    struct person: Codable {
        var name: String
        var age: Int
        var street: String
        var state: String
    
        private enum CodingKeys: String, CodingKey {
            case name
            case age
            case street = "Street_name"
            case state
        } }
    

提交回复
热议问题