基于 Swift 2.0 新特性(Protocol Extensions and Error Handling)的JSON 解析类。
示例代码:
定义结构体
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 {}
调用toJSON()方法,即可获取JSON格式的数据
let dict = try user.toJSON()
print("dict: \(dict)") 输出结果
[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;
}
)]