本文介绍了如何使用Codable和Swift解析此嵌套的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Codable解析此JSON:
I am trying to parse this JSON using Codable:
{ "users": [ { "id": 1, "name": "Allen Carslake", "userName": "acarslake0", "profileImage": "source.unsplash/random/400x400", "createdDate": "2019-07-08T00:00:00.000+0000" }, { "id": 2, "name": "Revkah Antuk", "userName": "rantuk1", "profileImage": "source.unsplash/random/400x400", "createdDate": "2019-07-05T00:00:00.000+0000" }, { "id": 3, "name": "Mirna Saffrin", "userName": "msaffrin2", "profileImage": "source.unsplash/random/400x400", "createdDate": "2019-05-19T00:00:00.000+0000" }, { "id": 4, "name": "Haily Eilers", "userName": "heilers3", "profileImage": "source.unsplash/random/400x400", "createdDate": "2019-06-28T00:00:00.000+0000" }, { "id": 5, "name": "Oralie Polkinhorn", "userName": "opolkinhorn4", "profileImage": "source.unsplash/random/400x400", "createdDate": "2019-06-04T00:00:00.000+0000" } ] }我在此处将URL保留为私有,但是它在上面返回JSON.到目前为止,这是我的代码:
I am keeping the URL private on here but it is returning JSON above. So far this is my code:
import UIKit struct User: Codable { let id: Int let name: String let userName: String let profileImage: String let createdDate: String } struct Users: Codable { let users: String } let url = URL(string: "")! URLSession.shared.dataTask(with: url) { data, _, _ in if let data = data { let users = try? JSONDecoder().decode([User].self, from: data) print(users) } }.resume()我需要能够访问User属性,但是我认为嵌套对我来说很困难.任何帮助都很棒!!谢谢!!
I need to be able to access the User properties but I think the nesting is making it difficult for me. Any help is awesome!! Thank you!!
推荐答案首先: Catch始终是DecodingError和print.它会告诉您确切的问题.
First of all: Catch always the DecodingError and print it. It tells you exactly what's wrong.
发生此错误是因为您忽略了根对象Users.如果您decode(Users.self,您的代码将起作用.
The error occurs because you are ignoring the root object Users. Your code works if you decode(Users.self.
我的建议:
- 将createdDate解码为Date,添加适当的日期解码策略.
- 将profileImage解码为URL(免费).
- 处理所有错误.
- Decode createdDate as Date adding a appropriate date decoding strategy.
- Decode profileImage as URL (for free).
- Handle all errors.
更多推荐
如何使用Codable和Swift解析此嵌套的JSON?
发布评论