28

I'm using an API that returns JSON that looks like this

{
   "boards":[
      {
         "attribute":"value1"
      },
      {
         "attribute":"value2"
      },
      {
         "attribute":"value3",
      },
      {
         "attribute":"value4",
      },
      {
         "attribute":"value5",
      },
      {
         "attribute":"value6",
      }
   ]
}

In Swift I use two functions to get and then parse the JSON

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
    return boardsDictionary
}

and then I call it using

var parsedJSON = parseJSON(getJSON("link-to-API"))

The JSON is parsed fine. When I print out

println(parsedJSON["boards"])

I get all the contents of the array. However I am unable to access each individual index. I'm positive it IS an Array, because ween I do

parsedJSON["boards"].count

the correct length is returned. However if I attempt to access the individual indices by using

parsedJSON["boards"][0]

XCode turns off syntax highlighting and gives me this:

XCode Error

and the code won't compile.

Is this a bug with XCode 6, or am I doing something wrong?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
plv
  • 949
  • 2
  • 8
  • 12
  • parsedJSON["boards"][0] is surely objective-c literal but is it also swift syntax? not sure about that (but i guess it is) – Nicolas Manzini Jun 03 '14 at 22:57
  • 5
    It seems like there are several bugs related to arrays of dictionaries at this point. I'm currently beating my head against it as well. – David Berry Jun 03 '14 at 23:47
  • 1
    Your parseJson function will crash if there is an error parsing and nil is returned. The "as NSDictionary" is the culprit. See my answer here for correct syntax on how to parse JSON with NSJSONSerialization: http://stackoverflow.com/a/24333999/1687195 – user1687195 Jun 20 '14 at 20:21
  • Xcode crashes at strange times, it probably not your code. – μολὼν.λαβέ Apr 09 '15 at 19:23

4 Answers4

20

Dictionary access in Swift returns an Optional, so you need to force the value (or use the if let syntax) to use it.

This works: parsedJSON["boards"]![0]

(It probably shouldn't crash Xcode, though)

micahbf
  • 607
  • 4
  • 11
  • I'm rather looking for something like: myDto: MyDTO = getJson() println(myDto.field) println(myDto.anotherField) – Alex Jul 16 '14 at 11:15
9

Take a look here:https://github.com/lingoer/SwiftyJSON

let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
    //Now you got your value
}
6

You can create a variable

var myBoard: NSArray = parsedJSON["boards"] as! NSArray

and then you can access whatever you have in "boards" like-

println(myBoard[0])
Niloy Mahmud
  • 97
  • 1
  • 10
4

The correct way to deal with this would be to check the return from the dictionary key:

    if let element = parsedJSON["boards"] {
        println(element[0])
    }
voidref
  • 1,113
  • 11
  • 15