在我的 swift 应用程序中将 NSData 解析为 Json 失败

Parsing NSData to Json failed in my swift app

我通过以下代码从在线 API 获得了一个 NSData:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
        if error != nil {
            print("\(error)")
            return
        }  
        let res = NSString(data: data!, encoding: NSUTF8StringEncoding) 
            print("\(res)")
        }; 
task.resume()

数据看起来像这样(NSString 没问题):

{
"word": "detrimental",
"results": [
    {
        "definition": "(sometimes followed by `to') causing harm or injury",
        "partOfSpeech": "adjective",
        "synonyms": [
            "damaging",
            "prejudicial",
            "prejudicious"
        ],
        "similarTo": [
            "harmful"
        ],
        "derivation": [
            "detriment"
        ]
    }
],
"syllables": {
    "count": 4,
    "list": [
        "det",
        "ri",
        "men",
        "tal"
    ]
},
"pronunciation": {
    "all": ",dɛtrə'mɛntəl"
},
"frequency": 2.77
}

现在,我正在尝试将数据解析为 json。我尝试了一些方法,但都失败了。喜欢这个:

func getJSON(data:NSData) -> [[String:AnyObject]]{
    var json = [[String:AnyObject]]()
    do {
        json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[String:AnyObject]]
    } catch {}
    return json;
}

这个也失败了:(原因:无法将类型“__NSCFDictionary”(0xd755c0)的值转换为'NSArray'(0xd752f0) .)

func hiJson(data:NSData) -> NSArray {
    var json: NSArray!
    do {
        json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSArray
    } catch {
        print(error)
    }
    return json
}

有人能帮忙吗?

我确定它不是数组,而是字典。像这样解析为 Json:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary

要获取定义密钥,请执行此操作

res.valueForKeyPath("results.definition")