ios – In Swift5 with Codable, easily handle json key that begins with a dollar sign such as “$date”


Example, I often see this sort of thing,

                "Length": 0,
                "TestDate": {
                    "$date": "2023-09-20T05:00:00.0000000Z"
                },
                "Weight": 0,
                "Height": 0,

This works,

    struct DollarDate: Codable {
        let date: Date
        
        private enum CodingKeys: String, CodingKey {
            case date = "$date"
        }
    }

however, with Swift these days it’s usually not necessary to fuss with coding keys.

For example, if a key is a Swift keyword, you can just …

struct Draft: Codable {
    
    let id: String
    var `case`: Case?   // no problem these days, just use backtick
}

Is there a similar instant solution to problem key names like ” $date ” in json?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img