项目简介
JSON
为轻松在Swift3中解析JSON的微框架,带有丰富的错误信息提示,只有不到一百行。
Usage比方说我们有一个简单的用户结构:
struct User { let name: String let createdAt: Date } Deserializing Attributes我们可以轻松添加JSON反序列化:
extension User: JSONDeserializable { init(jsonRepresentation json: JSONDictionary) throws { name = try decode(json, key: "name") createdAt = try decode(json, key: "created_at") } }注意你无需修改类型。它使用Swift通用和模式匹配,
func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T func decode(_ dictionary: JSONDictionary, key: String) throws -> Date下面是返回一个Date的特殊版本.你可以对自定义类型应用你自己的函数 。
下面是行动中的反序列化:
let dictionary = [ "name": "Sam Soffes", "created_at": "2016-09-22T22:28:37+02:00" ] let sam = try User(jsonRepresentation: dictionary)当用户是JSONDeserializable时你可以直接按照如下操作.
let sam: User = try decode(dictionary) 可选属性解码一个可选的属性是很容易的:
struct Comment { let body: String let publishedAt: Date? } extension Comment { init(jsonRepresentation json: JSONDictionary) throws { body = try deocde(json, key: "body") // See how we use `try?` to just get `nil` if it fails to decode? // Easy as that! publishedAt = try? deocde(json, key: "published_at") } } 反串型嵌套字典结合嵌套模式运行是很轻松的。假设有如下post模式:
struct Post { let title: String let author: User } extension Post: JSONDeserializable { init(jsonRepresentation json: JSONDictionary) throws { title = try decode(json, key: "title") author = try decode(json, key: "author") } }我们可以像处理其他属性那样直接处理一个嵌套模式,因为JSONDeserializable包含一个通用函数。下面是有注释的实现:
public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary, key: String) throws -> T { // Decode the value like normal as a JSONDictionary. If this fails for whatever // reason, it will throw the appropriate errors. let value: JSONDictionary = try decode(dictionary, key: key) // Decode the model. This will call the initializer in the protocol for the // expected type. If decoding fails in the model, this will also throw the // appropriate erros. return try decode(value) } 反序列化自定义类型假设你有如下枚举:
enum RelationshipStatus: String { case stranger case friend case blocked }你可以轻松为这个类型定义decode函数:
func decode(_ dictionary: JSONDictionary, key: String) throws -> RelationshipStatus { let string: String = try decode(dictionary, key: key) guard let status = RelationshipStatus(rawValue: string) else { throw JSONDeserializationError.invalidAttribute(key: key) } return status }然后你可以正常操作try decode(dictionary, key: "status"),它将会抛出适当的错误.
项目首页 添加收藏