在swift 4中解码嵌套数组
发布时间:2020-12-14 02:24:33 所属栏目:百科 来源:网络整理
导读:参见英文答案 JSON parsing in Swift 4 with complex nested data2个 采用以下JSON: let rawJson ="""[ { "id": 1,"name":"John Doe" },{ "id": 2,"name":"Luke Smith" },]""" 和用户模型: struct User: Decodable { var id: Int var name: String} 解码非
参见英文答案 >
JSON parsing in Swift 4 with complex & nested data2个
采用以下JSON: let rawJson = """ [ { "id": 1,"name":"John Doe" },{ "id": 2,"name":"Luke Smith" },] """ 和用户模型: struct User: Decodable { var id: Int var name: String } 解码非常简单,如下所示: let data = rawJson.data(using: .utf8) let decoder = JSONDecoder() let users = try! decoder.decode([User].self,from: data!) 但是如果JSON看起来像这样,顶级是一个字典并需要获取用户数组: let json = """ { "users": [ { "id": 1,"name":"John Doe" },"name":"Luke Smith" },] } """ 阅读JSON最有效的解决方案是什么?我当然可以创建另一个这样的结构: struct SomeStruct: Decodable { var posts: [Post] } 并解码如下: let users = try! decoder.decode(SomeStruct.self,from: data!) 但是这样做感觉不对,只是因为数组嵌套在字典中而创建一个新的模型对象.
如果你想利用JSONDecoder,你必须创建一个嵌套的struct(ure).
我建议为根对象使用名称Root,并将子结构放入Root struct Root : Decodable { struct User : Decodable { let id: Int let name: String } let users : [User] } let json = """ { "users": [{"id": 1,"name":"John Doe"},{"id": 2,"name":"Luke Smith"}] } """ let data = Data(json.utf8) do { let root = try JSONDecoder().decode(Root.self,from: data) print(root.users) } catch { print(error) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |