如何解析Swift中解析的JSON中的数组? [英] How do I parse an array inside parsed JSON in Swift?

查看:122
本文介绍了如何解析Swift中解析的JSON中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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",
      }
   ]
}

在Swift中我使用两个函数来获取然后解析JSON

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
}

然后我用

var parsedJSON = parseJSON(getJSON("link-to-API"))

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

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

XCode turns off syntax highlighting and gives me this:

且代码无法编译。

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

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

推荐答案

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

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

这适用:
parsedJSON [boards]![0]

(尽管可能不会崩溃Xcode)

(It probably shouldn't crash Xcode, though)

这篇关于如何解析Swift中解析的JSON中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆