我是swift的新手。我创建了简单的playground并将扩展名为json的文件添加到playground中。我尝试使用for循环解码结果并打印ID,但是,我收到以下错误..For-in循环要求“People.Type "符合”Sequence“
这是我的json文件。
{
"id": "1",
"options": [{
"id": "11",
"options": [{
"id": "111",
"options": []
}]
},
{
"id": "2",
"options": [{
"id": "21",
"options": []
},
{
"id": "22",
"options": [{
"id": "221",
"options": []
}]
}
]
}
]
}
这里是代码..我试过..
struct People: Codable {
let id: String
let options: [People]
}
func loadJson(filename fileName: String) -> People? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(People.self, from: data)
print("// Printing the ID of the Decode Json")
for jsondata in jsonData {
print("ID: \(jsonData.id)")
}
return jsonData
} catch {
print("error:\(error)")
}
}
return nil
}
loadJson(filename: "people1")
下面是错误的屏幕截图。
1条答案
按热度按时间lc8prwob1#
在这里,我运行的正是您所要求的,但是我认为您可能应该考虑将您的结构体重命名为像@Vadian建议的
Person
。这将打印: