“[Root]”类型的值没有成员“commit”。我如何解码 JSON 根数组
Posted
技术标签:
【中文标题】“[Root]”类型的值没有成员“commit”。我如何解码 JSON 根数组【英文标题】:Value of type '[Root]' has no member 'commit'. How can i decode JSON root array 【发布时间】:2018-08-12 10:36:45 【问题描述】:我正在尝试使用可编码解析 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(commit: Gihhub.Author(author: Gihhub.People(name: Optional("Slava Pestov"), date: Optional("2018-08-12T08:09:22Z")), email: Optional (“sviatoslav.pestov@gmail.com”)))),Gihhub.Commits(提交:Gihhub.Author(作者:Gihhub.People(名称:可选(“Slava Pestov”),日期:可选(“2018-08- 12T03:47:22Z"),电子邮件:可选(“spestov@apple.com”)))),Gihhub.Commits(提交:Gihhub.Author(作者:Gihhub.People(名称:可选(“Slava Pestov”)),日期:可选(“2018-08-12T03:47:08Z”),电子邮件:可选(“spestov@apple.com”))))]
【问题讨论】:
结构的命名有点混乱。应该是struct Root: Decodable let commit: Commit
struct Commit: Decodable let author: Author
struct Author: Decodable let name: String; let date: String; let email: String
。所有结构成员都可以是非可选的。如果添加日期解码策略.iso8601
,则可以将date
解码为Date
PS:请从24:00开始观看WWDC 2017 Session 212 : What's new in Foundation。你会看到非常熟悉的东西。
@vadian 非常感谢你,我已经看过并改进了我的代码。干杯
【参考方案1】:
结果是你需要的数组
result.forEach
print($0.commit.author.name)
print($0.commit.author.date)
print($0.commit.author.email)
【讨论】:
非常感谢。忘记循环了。效果很好。以上是关于“[Root]”类型的值没有成员“commit”。我如何解码 JSON 根数组的主要内容,如果未能解决你的问题,请参考以下文章
“任何”的值类型没有成员 'objectforKey' Swift 3 转换
Swift 3 - 'Any?' 类型的值没有成员“valueForKey”
“String”类型的值没有成员“stringByAppendingPathComponent”[重复]
Xcode 13:`'NSPersistentCloudKitContainerOptions' 类型的值没有成员'databaseScope'`