MetovaJSONCodable
MetovaJSONCodable 是一个轻量级的 Codable 协议,并增加了对 JSON 的支持
要求
- Swift 4.2
- iOS 9+
安装
MetovaJSONCodable 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile
pod 'MetovaJSONCodable'
使用
任何之前遵守 Codable 协议的对象现在都可以使用 JSONCodable 协议。
对象示例
struct Token: JSONCodable {
var tokenID: Int
var email: String
var authenticationToken: String
}
JSON
let tokenJSON: JSON = [
"testID": 1,
"email": "[email protected]",
"authenticationToken": "token"
]
let token = Token(from: tokenJSON)
自定义日期处理
该数据包包含用于处理自定义日期格式的 JSON 的几个子协议
参考日期以来的时间间隔
struct Token: JSONEpochDateCodable {
var tokenID: Int
var email: String
var authenticationToken: String
var expirationDate: Date
}
let tokenJSON: JSON = [
"tokenID": 1,
"email": "[email protected]",
"authenticationToken": "token",
"expirationDate": 1523560533
]
let token = Token(from: tokenJSON)
// token.expirationDate is a Date equaling 2018-04-12 19:15:33 +0000
自定义日期格式化对象
我们还有一个子协议支持自定义日期格式化。在这里,您需要实现一个返回日期格式化的 computed 变量,以符合该协议
struct Token: JSONCustomDateFormatterCodable {
var testID: Int
var email: String
var expirationDate: Date
static var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return dateFormatter
}
}
let validTestJSONISO8601: JSON = [
"testID": 2,
"email": "[email protected]",
"expirationDate": "2016-12-31T17:56:27.000Z"
]
let token = Token(from: tokenJSON)
// token.expirationDate is a Date equaling 2016-12-31 17:56:27 +0000
自定义子协议
如果您想定义自己的日期格式化策略或默认编码/解码器的一些其他变体,您只需创建一个子协议并实现自己的编码器/解码器
public protocol JSONDecodeableIOS8601: JSONDecodable {}
public extension JSONDecodeableIOS8601 {
static var jsonDecoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
}
文档
文档信息可在此处找到。
致谢
MetovaJSONCodable 由 Metova Inc. 所有和维护。
授权
MetovaJSONCodable 在MIT授权协议下提供。有关更多信息,请参阅LICENSE文件。