如何使用Codable和Swift解析此嵌套的JSON? [英] How do I parse this nested JSON using Codable with Swift?

查看:221
本文介绍了如何使用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始终是DecodingErrorprint.它会告诉您确切的问题.

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.
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()

这篇关于如何使用Codable和Swift解析此嵌套的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆