JSONEncoder's dateEncodingStrategy not working

后端 未结 2 1453
清歌不尽
清歌不尽 2021-01-22 04:45

I am trying to serialize a struct to a String using Swift 4\'s Encodable+JSONEncoder. The object can hold heterogenous values like String, Array, Date, Int etc.

The use

2条回答
  •  执念已碎
    2021-01-22 05:28

    You can eliminate the EncodableValue wrapper, and use a generic instead:

    struct Bar: Encodable {
        let key: String
        let value: T?
    
        var json: String {
            let encoder = JSONEncoder()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "E, d MMM yyyy"
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
            encoder.dateEncodingStrategy = .formatted(dateFormatter)
            let data = try! encoder.encode(self)
            return String(data: data, encoding: .utf8)!
        }
    }
    
    let bar = Bar(key: "date", value: Date())
    
    print(bar.json)
    

    That yields:

    {"key":"date","value":"Wed, 7 Feb 2018"}
    

提交回复
热议问题