ios 如何在 Swift 中解析已解析的 JSON 中的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24026305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:20:48  来源:igfitidea点击:

How do I parse an array inside parsed JSON in Swift?

iosjsonswift

提问by Paul Vorobyev

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

我正在使用一个返回 JSON 的 API,它看起来像这样

{
   "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

在 Swift 中,我使用两个函数来获取然后解析 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

JSON 解析得很好。当我打印出来

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 关闭语法高亮并给我这个:

XCode Error

XCode 错误

and the code won't compile.

并且代码不会编译。

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

这是 XCode 6 的错误,还是我做错了什么?

采纳答案by micahbf

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

Swift 中的字典访问返回一个 Optional,因此您需要强制该值(或使用if let语法)来使用它。

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

这有效: parsedJSON["boards"]![0]

(It probably shouldn't crash Xcode, though)

(不过,它可能不应该使 Xcode 崩溃)

回答by user3764120

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

看看这里:https: //github.com/lingoer/SwiftyJSON

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

回答by Niloy Mahmud

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

回答by voidref

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