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

时间:2016-05-21 18:53:29

标签: ios json swift nsdata nsjsonserialization

我通过以下代码从在线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
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

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

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

要获得定义键,请执行此操作

res.valueForKeyPath("results.definition")