Search code examples
jsonswiftswift2nsarray

Retrieving values from 2D array in JSON string


We fetch some JSON data using a REST protocol like this.

jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)

Which looks like this:

jsonResult: (
    {
    board = "[[\"1:\",\"Y\",\"U\",\"P\"]]";
})

From this we get a game board like so:

     if let boardContentArray = jsonResult[0]["board"] as NSArray?{
        print("boardContentArray: \(boardContentArray)" )
    } else {
        print("board element is not an NSArray")
    }

The boardContentArray looks like this: It i supposed to be a 2D array with only one row and four columns at the moment, but it should should work for any given size.

[["1:","Y","U","P"]]

How can you retrieve the individual values of boardFromRemote. I imagine to get the element at 0,0 in the 2D array some way like this:

boardContentArray[0][0]

This should then return "1:", which is not the case. This exact syntax is incorrect and won't compile. What is the correct way to retrieve an element from the boardContentArray variable?


Solution

  • The content of jsonResult[0]["board"] is a JSON String which can be decoded as an array with NSJSONSerialization. You have to first transform the String to NSData, then decode it like this for example:

    do {
        let boardContentArray = "[[\"1:\",\"Y\",\"U\",\"P\"]]" // the String from jsonResult[0]["board"]
        if let boardData = boardContentArray.dataUsingEncoding(NSUTF8StringEncoding),
            let boardArray = try NSJSONSerialization.JSONObjectWithData(boardData, options: []) as? [[String]] {
                print(boardArray[0]) // ["1:", "Y", "U", "P"]
        }
    } catch let error as NSError {
        print(error)
    }