[英]swift SwiftyJSON to get value
I have a json string: let jsonStr = {"username":"Jame"}
, and I use swiftyJson: let json = JSON(jsonStr)
. 我有一个json字符串:
let jsonStr = {"username":"Jame"}
,我使用swiftyJson: let json = JSON(jsonStr)
。 Now I want to get the username, so I try json["username"].string
, but the result is nil. 现在,我想获取用户名,因此尝试使用
json["username"].string
,但结果为nil。
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. 如果
jsonStr
只是String,则需要将String转换为Dictionary。 JSON
initializer requires instance of Dictionary. JSON
初始化程序需要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 !
更安全的是,如果使用
if let
, do{} catch(let e){}
而不是!
, try!
try!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.