Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftyJSON dictionary parsing

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.

like image 246
coldbuffet Avatar asked Dec 12 '22 01:12

coldbuffet


2 Answers

What you should do is:

if let username = json["data"]["username"].string {
    println(username)
}
like image 67
fz. Avatar answered Jan 05 '23 15:01

fz.


While the above will work, The real issue was you needed to unpack the dict value:

let username = data["username"]!.stringValue

like image 34
John Avatar answered Jan 05 '23 14:01

John