从JSON字符串中的2D数组中检索值

时间:2022-06-15 21:37:03

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

我们使用这样的REST协议获取一些JSON数据。

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.

boardContentArray看起来是这样的:它应该是一个只有一行和四列的2D数组,但是它应该适合任何给定的大小。

[["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:

如何检索boardFromRemote的各个值。我想象一下在二维数组中以这样的方式得到元素(0,0)

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?

然后应该返回“1:”,但事实并非如此。这个确切的语法是不正确的,不能编译。从boardContentArray变量中检索元素的正确方法是什么?

1 个解决方案

#1


2  

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:

jsonResult[0]["board"]的内容是一个JSON字符串,可以用NSJSONSerialization将其解码为一个数组。你必须首先将字符串转换为NSData,然后像这样解码:

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

#1


2  

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:

jsonResult[0]["board"]的内容是一个JSON字符串,可以用NSJSONSerialization将其解码为一个数组。你必须首先将字符串转换为NSData,然后像这样解码:

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