【发布时间】:2023-03-29 02:05:01
【问题描述】:
我想解析一个本地 JSON 文件,但我不知道如何在 Swift 3 中执行此操作
我当前的代码似乎不起作用
我不断收到此错误:
'jsonObject' 产生'Any',而不是预期的上下文结果类型'NSArray'
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController
{
var allEntries: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func LoadAllQuestionsAndAnswers
{
let path = Bundle.main.path(forResource: "content", ofType: "json")
let jsonData : NSData = NSData(contentsOfFile: path!)!
allEntries = JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil) as String
NSLog(allEntries)
}
}
我正在从这个 json 文件“content.json”加载数据
[
{
"id" : "1",
"question": "What is the fastest fish in the ocean?",
"answers": [
"Sailfish",
"Lion Fish",
"Flounder",
"Tiger Shark",
"Swordfish"
],
"difficulty": "1"
},
{
"id" : "2",
"question": "Which animal has the most legs?",
"answers": [
"Millipede",
"Shrimp",
"Octopus",
"Dog",
"Lion"
],
"difficulty": "1"
}
]
【问题讨论】:
-
您使用的代码甚至无法编译,因为从 Swift 2 开始,此方法没有类似错误的参数,而是您需要使用 try catch 将其抛出。
标签: json swift parsing swift3 xcode8