如何使用Codable和Swift解析此嵌套的JSON?
问题描述:
我正在尝试使用Codable解析此JSON:
I am trying to parse this JSON using Codable:
{
"users": [
{
"id": 1,
"name": "Allen Carslake",
"userName": "acarslake0",
"profileImage": "https://source.unsplash.com/random/400x400",
"createdDate": "2019-07-08T00:00:00.000+0000"
},
{
"id": 2,
"name": "Revkah Antuk",
"userName": "rantuk1",
"profileImage": "https://source.unsplash.com/random/400x400",
"createdDate": "2019-07-05T00:00:00.000+0000"
},
{
"id": 3,
"name": "Mirna Saffrin",
"userName": "msaffrin2",
"profileImage": "https://source.unsplash.com/random/400x400",
"createdDate": "2019-05-19T00:00:00.000+0000"
},
{
"id": 4,
"name": "Haily Eilers",
"userName": "heilers3",
"profileImage": "https://source.unsplash.com/random/400x400",
"createdDate": "2019-06-28T00:00:00.000+0000"
},
{
"id": 5,
"name": "Oralie Polkinhorn",
"userName": "opolkinhorn4",
"profileImage": "https://source.unsplash.com/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
asDate
adding a appropriate date decoding strategy. - Decode
profileImage
asURL
(for free). - Handle all errors.
struct Root : Decodable { // `Users` and `User` is too confusing
let users: [User]
}
struct User : Decodable {
let id: Int
let name: String
let userName: String
let profileImage: URL
let createdDate: Date
}
URLSession.shared.dataTask(with: url) { data, _, error in
if let error = error { print(error); return }
do {
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let result = try decoder.decode(Root.self, from: data!)
for user in result.users {
print(user.userName, user.id, user.createdDate)
}
} catch {
print(error)
}
}.resume()