从JSON字符串中的2D数组中检索值 [英] Retrieving values from 2D array in JSON string
问题描述
我们使用这样的REST协议获取一些JSON数据.
We fetch some JSON data using a REST protocol like this.
jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
看起来像这样:
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")
}
boardContentArray看起来像这样:现在我应该是一个只有一行四列的2D数组,但是它应该适用于任何给定的大小.
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"]]
如何检索boardFromRemote的各个值.我想像这样将2D数组中的元素设置为0,0:
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]
然后应返回"1:" ,事实并非如此.此确切的语法不正确,无法编译.从boardContentArray变量检索元素的正确方法是什么?
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?
推荐答案
jsonResult[0]["board"]
的内容是 JSON字符串,可以使用NSJSONSerialization解码为数组.您必须首先将String转换为NSData,然后像这样将其解码:
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)
}
这篇关于从JSON字符串中的2D数组中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!