Jar*_*red 4 parsing json swift
我正在编写一个刽子手游戏,并使用json文本文件将可能的单词加载到我的应用程序中.我试图在这个网站上关注其他人的例子,但我从Xcode收到错误.
我根据另一个答案尝试了以下代码:
import Foundation
var error: NSError?
let jsonData: NSData = /* get your json data */
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
Run Code Online (Sandbox Code Playgroud)
但是我在第4行遇到了一个错误,jsonDict说"调用可以抛出,但没有标记为try,并且错误未被处理"和"Type JSONReadingOptions不符合协议NilLiteralConvertible".
这是我要解析的JSON文件:
{
“wordList” : {
“difficulty” : “Easy”
“list” : [
“fireplace”,
“apple”,
“january”,
“tooth”,
“cookies”,
“mysterious”,
“essential”,
“magenta",
“darling”,
“pterodactyl”
]}}
Run Code Online (Sandbox Code Playgroud)
我希望能够进入我的列表数组并获取值.非常感谢您的帮助!
在Swift 2中,您需要使用新的错误处理API,而不是将引用传递给NSError:
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
if let jsonDict = jsonDict {
// work with dictionary here
} else {
// more error handling
}
} catch let error as NSError {
// error handling
}
Run Code Online (Sandbox Code Playgroud)
您也不能将nil值作为值传递给options参数,您需要传递一个值类型NSJSONReadingOptions.
也就是说,在Swift中解析JSON的最常用方法是使用第三方库,例如Argo因为它们可以为您节省大量代码,这些代码是验证并安全地将JSON数据的内容转换为正确的Swift类型所必需的.
| 归档时间: |
|
| 查看次数: |
4663 次 |
| 最近记录: |