歡迎加入QQ討論群258996829

Swift JSON 解析(對(duì)象映射)庫(kù) Decodable

發(fā)布時(shí)間:2016-04-11 11:10  回復(fù):0  查看:3853  感興趣:9  贊:0   最后回復(fù):2016-04-11 11:10  

Swift JSON 解析(對(duì)象映射)庫(kù) Decodable。

示例代碼:

struct Repository {
    let name: String
    let description: String
    let stargazersCount: Int
    let language: String?
    let sometimesMissingKey: String?

    let owner: User // Struct conforming to Decodable
    let defaultBranch: Branch // Struct NOT conforming to Decodable

    var fullName: String { return "\(owner.login)/\(name)" }
}

extension Repository: Decodable {
    static func decode(j: AnyObject) throws -> Repository {
        return try Repository(
                    name: j => "name", 
                    description: j => "description", 
                    stargazersCount: j => "stargazers_count", 
                    language: j => "language", 
                    sometimesMissingKey: j =>? "sometimesMissingKey",
                    owner: j => "owner", 
                    defaultBranch: Branch(name: j => "default_branch")
                )
    }
}

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
    let repo = try Repository.decode(json)
} catch {
    print(error)
}

相關(guān)開(kāi)源代碼

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

熱門帖子

最新帖子

?