我正在使用返回看起来像这样的JSON的API
{
"boards":[
{
"attribute":"value1"
},
{
"attribute":"value2"
},
{
"attribute":"value3",
},
{
"attribute":"value4",
},
{
"attribute":"value5",
},
{
"attribute":"value6",
}
]
}
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
然后我用它来调用它
var parsedJSON = parseJSON(getJSON("link-to-API"))
Run Code Online (Sandbox Code Playgroud)
JSON被解析得很好.当我打印出来
println(parsedJSON["boards"])
Run Code Online (Sandbox Code Playgroud)
我得到了数组的所有内容.但是我无法访问每个索引.我很肯定它是一个数组,因为我做了
parsedJSON["boards"].count
Run Code Online (Sandbox Code Playgroud)
返回正确的长度.但是,如果我尝试通过使用访问各个索引
parsedJSON["boards"][0]
Run Code Online (Sandbox Code Playgroud)
XCode关闭语法高亮,并给我这个:

并且代码不会编译.
这是XCode 6的错误,还是我做错了什么?
mic*_*hbf 20
Swift中的字典访问返回一个Optional,因此您需要强制该值(或使用if let语法)来使用它.
这有效:
parsedJSON["boards"]![0]
(但它可能不应该崩溃Xcode)
小智 9
看看这里:https://github.com/lingoer/SwiftyJSON
let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
//Now you got your value
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以创建变量
var myBoard: NSArray = parsedJSON["boards"] as! NSArray
Run Code Online (Sandbox Code Playgroud)
然后你可以访问"董事会"中你拥有的任何东西 -
println(myBoard[0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52765 次 |
| 最近记录: |