json - 如何快速从本地 JSON 文件中获取数据?
问题描述
我想从本地 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)
}
}
解决方案
您必须注意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
.
推荐阅读
- node.js - npm 每次运行时都会给出一个 TypeError
- java - 如果我的角色在地面或平台上,如何让我的角色跳跃相同的高度?(JSFML)
- javascript - 确定在二进制搜索中使用什么索引变量的模式?
- python - python3试图获得多行输入
- node.js - AWS Lambda,调用处理程序之前的延迟
- c# - 无法使用涉及多重继承的对象访问基类中的正确属性
- python - 递归函数中的返回行为
- python - 如何在使用 EfficientNet 时防止过拟合/欠拟合
- telnet - Metasploit中的远程主机强制关闭现有连接是什么意思?
- python - Keyerror:None,我不明白这个问题