欢迎加入QQ讨论群258996829

JSON解析类JSONCodable

发布时间:2016-01-04 14:06  回复:0  查看:4242  感兴趣:7  赞:0   最后回复:2016-01-04 14:06  

基于 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;
    }
)]

相关开源代码

您还未登录,请先登录

热门帖子

最新帖子