Jared
Jared

Reputation: 588

Swift 2.0 How to parse JSON?

I am coding a hangman game and am loading the possible words into my app using json text files. I tried to follow the examples of others on this website but I am getting errors from Xcode.

I tried the following code based on another answer:

import Foundation

var error: NSError?
let jsonData: NSData = /* get your json data */

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil,   error: &error) as NSDictionary

But I got an errors on line 4 with jsonDict that said "call can throw but is not marked with try, and the error is not handled" and "Type JSONReadingOptions does not conform to protocol NilLiteralConvertible".

Here is the JSON File I would like to parse:

{
“wordList” : {
    “difficulty” : “Easy”
    “list” : [
        “fireplace”,
        “apple”,
        “january”,
        “tooth”,
        “cookies”,
        “mysterious”,
        “essential”,
        “magenta",
        “darling”,
        “pterodactyl”
    ]}}

I would like to be able to go into my list array and get values. Thank you very much for any help!

Upvotes: 4

Views: 4679

Answers (1)

Ben-G
Ben-G

Reputation: 5026

In Swift 2 you need to use the new error handling API instead of passing a reference to an NSError:

do {
  let jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
  if let jsonDict = jsonDict {
     // work with dictionary here
  } else {
     // more error handling
  }
} catch let error as NSError {
  // error handling
}

You also can't pass nil as value to the options parameter, you need to pass a value of type NSJSONReadingOptions.

That said, the most common approach for parsing JSON in Swift is currently using third party libraries, such as Argo because they can save you a lot of code that is necessary to validate and safely cast the content of your JSON data to the correct Swift types.

Upvotes: 5

Related Questions