欢迎加入QQ讨论群258996829

Swift JSON 解析(对象映射)库 Decodable

发布时间:2016-04-11 11:10  回复:0  查看:2178  感兴趣:9  赞:0   最后回复:2016-04-11 11:10  

Swift JSON 解析(对象映射)库 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)
}

相关开源代码

您还未登录,请先登录

热门帖子

最新帖子