类型“ [Root]”的值没有成员“ commit”。我如何解码JSON根数组

时间:2018-08-12 10:36:46

标签: ios json swift git codable

我正在尝试使用可编码来解析JSON。我能够对其进行解码,但是它在根数组中,因此我无法自行打印每个值。编译器抱怨说Value of type '[Root]' has no member 'commit'。我该如何更改以打印值。下面是JSON

[
    {
        "sha": "3f4227ec2894bb354b145deff9dbc1adc6b6d6f2",
        "node_id": "MDY6Q29tbWl0NDQ4Mzg5NDk6M2Y0MjI3ZWMyODk0YmIzNTRiMTQ1ZGVmZjlkYmMxYWRjNmI2ZDZmMg==",
        "commit": {
            "author": {
                "name": "Slava Pestov",
                "email": "sviatoslav.pestov@gmail.com",
                "date": "2018-08-12T08:09:22Z"
            }
        }
    },
    {
        "sha": "3f4227ec2894bb354b145deff9dbc1adc6b6d6f2",
        "node_id": "MDY6Q29tbWl0NDQ4Mzg5NDk6M2Y0MjI3ZWMyODk0YmIzNTRiMTQ1ZGVmZjlkYmMxYWRjNmI2ZDZmMg==",
        "commit": {
            "author": {
                "name": "Slava Pestov",
                "email": "sviatoslav.pestov@gmail.com",
                "date": "2018-08-12T08:09:22Z"
            }
        }
    }
]

我在这里解码

struct Root: Decodable {
    let commit: Author
}

struct Author: Decodable {
    let author: People
}

struct People: Decodable {
    let name: String?
    let date: String?
    let email: String?
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        getCommits()
    }


    func getCommits() {
        let urlString = "https://api.github.com/repos/apple/swift/commits"
        guard let url = URL(string: urlString) else {
            print("Couldn't fetch JSON")
            return
        }
        let session = URLSession.shared
        let dataTask = session.dataTask(with: url) { (data, response, error) in
            guard data != nil && error == nil else {
                print(data ?? "")
                return
            }
            do {
                let decoder = JSONDecoder()
                let result = try decoder.decode([Root].self, from: data!)
                print(result.commit)
                print(result.commit.author.name)
            } catch let decodeError {
                print("Failed to decode json:", decodeError)
            }
        }
        dataTask.resume()
    }
}

这是我在控制台中的输出。我只想打印姓名,日期和电子邮件。

  

[Gihhub.Commits(提交:Gihhub.Author(作者:Gihhub.People(名称:Optional(“ Slava Pestov”),日期:Optional(“ 2018-08-12T08:09:22Z”),电子邮件:Optional) (“ sviatoslav.pestov@gmail.com”))))),Gihhub.Commits(提交:Gihhub.Author(作者:Gihhub.People(名称:Optional(“ Slava Pestov”)),日期:Optional(“ 2018-08- 12T03:47:22Z“),电子邮件:Optional(” spestov@apple.com“))))),Gihhub.Commits(commit:Gihhub.Author(作者:Gihhub.People(名称:Optional(” Slava Pestov“)),日期:Optional(“ 2018-08-12T03:47:08Z”),电子邮件:Optional(“ spestov@apple.com”))))))]

1 个答案:

答案 0 :(得分:2)

结果是您需要的数组

result.forEach {
    print($0.commit.author.name)
    print($0.commit.author.date)
    print($0.commit.author.email)
}