Search code examples
iosjsonswiftnsdatansjsonserialization

Parsing NSData to Json failed in my swift app


I got a NSData from an online API by the following code:

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()

The data looks like this (NSString is ok):

{
"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
}

Now, I'm attempting to parse the data into json. I have tried some ways but all failed. Like this one:

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

and this one is also failed: (Reason: Could not cast value of type '__NSCFDictionary' (0xd755c0) to '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
}

Can anyone help?


Solution

  • I'm certain that it isn't an array, its a dictionary. Parse to Json like this:

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

    And to get definition key, do this

    res.valueForKeyPath("results.definition")