Chris Levely Chris Levely - 1 year ago 178
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() {
// Do any additional setup after loading the view, typically from a nib.

override func 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


I am loading the data from this json file "content.json"

"id" : "1",
"question": "What is the fastest fish in the ocean?",
"answers": [
"Lion Fish",
"Tiger Shark",
"difficulty": "1"
"id" : "2",
"question": "Which animal has the most legs?",
"answers": [
"difficulty": "1"

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download