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?

4
  • parsedJSON["boards"][0] is surely objective-c literal but is it also swift syntax? not sure about that (but i guess it is) Commented Jun 3, 2014 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. Commented Jun 3, 2014 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: stackoverflow.com/a/24333999/1687195 Commented Jun 20, 2014 at 20:21
  • Xcode crashes at strange times, it probably not your code. Commented Apr 9, 2015 at 19:23

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm rather looking for something like: myDto: MyDTO = getJson() println(myDto.field) println(myDto.anotherField)
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
}

Comments

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])

1 Comment

anytime you cast the parsed data to array you get an error.
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])
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.