歡迎加入QQ討論群258996829

JSON解析類JSONCodable

發(fā)布時(shí)間:2016-01-04 14:06  回復(fù):0  查看:4419  感興趣:7  贊:0   最后回復(fù):2016-01-04 14:06  

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

相關(guān)開源代碼

您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?