fcbflying
fcbflying

Reputation: 703

swift SwiftyJSON to get value

I have a json string: let jsonStr = {"username":"Jame"}, and I use swiftyJson: let json = JSON(jsonStr). Now I want to get the username, so I try json["username"].string, but the result is nil.

Upvotes: 0

Views: 283

Answers (1)

su-
su-

Reputation: 58

First, You should use

let jsonStr = "{\"username\":\"Jame\"}"

instead of

let jsonStr = {"username":"Jame"}

If jsonStr is just String, you need to convert String to Dictionary. JSON initializer requires instance of Dictionary. try this:

let jsonStr = "{\"username\":\"Jame\"}" // string
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)! // string->NSData
let jsonDic = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) // NSData->Dictionary
let json = JSON(jsonDic) // good!
print(json)
let name = json["username"].string
print(name) // Optional("Jame")

More safely, you use if let, do{} catch(let e){} instead of !,try!

Upvotes: 1

Related Questions