我想解析一个本地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"
     }
]

最佳答案

json的根对象是一个数组

var allEntries = [[String:Any]]()
...
allEntries = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! [[String:Any]]

在swift中根本不需要mutableContainers

09-04 06:27