基于 Swift 2.0 新特性(Protocol Extensions and Error Handling)的JSON 解析類。
示例代碼:
定義結(jié)構(gòu)體
struct User { let id: Int let name: String var email: String? var company: Company? var friends: [User] = [] } struct Company { let name: String var address: String? }繼承JSONEncodable (或 JSONCodable ):
extension User: JSONEncodable { func toJSON() throws -> AnyObject { return try JSONEncoder.create({ (encoder) -> Void in try encoder.encode(id, key: "id") try encoder.encode(name, key: "full_name") try encoder.encode(email, key: "email") try encoder.encode(company, key: "company") try encoder.encode(friends, key: "friends") }) } } extension Company: JSONEncodable {}
調(diào)用toJSON()方法,即可獲取JSON格式的數(shù)據(jù)
let dict = try user.toJSON() print("dict: \(dict)")輸出結(jié)果
[full_name: John Appleseed, id: 24, email: john@appleseed.com, company: { address = "1 Infinite Loop, Cupertino, CA"; name = Apple; }, friends: ( { friends = ( ); "full_name" = "Bob Jefferson"; id = 27; }, { friends = ( ); "full_name" = "Jen Jackson"; id = 29; } )]