我想从本地JSON文件获取数据。看起来像:
[
[
{
"link": "link1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question1"
},
{
"link": "link2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question2"
}
]
]
如何分别考虑每个元素? 我该如何分别回答每个答案? 我想在表格视图中使用答案。 indexPath.row [1] = answer1 indexPath.row [2] = answer2 ...
let url = Bundle.main.url(forResource: "info", withExtension: "json")!
do {
let jsonData = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: jsonData)
print(json)
//let current = json["title"] as! [String: [String:Any]]
//for (key, currency) in current {
//let quest = currency["title"] as! String
//let img = currency["image"] as! String
//let ans = currency["answers"] as! [String]
//}
}
catch {
print(error)
}
}
答案 0 :(得分:0)
您必须注意JSON
结构以获取正确的值。请参见下面的代码片段,以了解如何在JSON
中解决您的问题。
let url = Bundle.main.url(forResource: "File", withExtension: "txt")!
do {
let jsonData = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: jsonData) as! [[[String: Any]]]
if let question1 = json.first?[0] {
print( question1["link"] as! String)
}
if let question2 = json.first?[1] {
print( question2["link"] as! String)
}
}
catch {
print(error)
}
因此,现在您知道如何获取实际数据。您应该创建一些Question
类。然后,您应该保留从文件中解析出的问题列表,并将该列表用于TableView
。