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) }