gpt4 book ai didi

json - 如何快速从本地JSON文件中获取数据?

转载 作者:行者123 更新时间:2023-11-28 14:35:00 25 4
gpt4 key购买 nike

我想从本地 JSON 文件中获取数据。它看起来像:

[
[
{
"link": "link1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question1"
},
{
"link": "link2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question2"
}
]
]

如何分别获取每个元素?我怎样才能分别接受每个答案?我想在表格 View 中使用答案。indexPath.row[1] = answer1indexPath.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)
}

}

最佳答案

您必须注意 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

关于json - 如何快速从本地JSON文件中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50945202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com