SwiftyJSON dictionary parsing

coldbuffet picture coldbuffet · Feb 10, 2015 · Viewed 8.7k times · Source

I am attempting to use SwiftyJSON to parse some data from a server.

For example, say the JSON returned from the server is:

{     
 "data":{  
     "id":"92",
     "name":"harry",
     "username":"Hazza"
   },
 "error":false
}

I would like to get the username string and so to do this I obtain the data object using:

let data = json["data"].dictionaryValue

Then in order to grab the username string I would expect to be able to do

let username = data["username"].stringValue

However this returns an error saying '(String, JSON) does not have a member named '.stringValue'.

Where am I going wrong with this seemingly simple problem?

Thank you.

Answer

fz. picture fz. · Feb 10, 2015

What you should do is:

if let username = json["data"]["username"].string {
    println(username)
}