Chris Levely Chris Levely - 1 month ago 40
JSON Question

Parsing Json Files in Swift 3

I would like to parse a local JSON file but I am unaware of how to do so in Swift 3

My Current Code doesn't seem to work

I keep receiving this error:


'jsonObject' produces 'Any', not the expected contextual result type '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)
}

}


I am loading the data from this json file "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"
}
]

Answer

The root object of the JSON is an array

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

mutableContainers is not needed at all in Swift