{"response":{"success":true,"access_token":"z5zbXVfaD4xOyTCLOwLIBPvuEYw7lQCUWb5U7l4KpCyXvbJkHv2jkyOZwk6RbJM7VS12d5NDImBeykygPBAa9o9FJgxUZk1Uc2Xp","access_level":"1"}}
如何单独解析响应?我想将每个对象都放在单独的变量中。我的代码:
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
}
catch(let e) {
print(e)
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
答案 0 :(得分:1)
对于简单的JSON解析,您可以使用NSJSONSerialization
var decodedJson : AnyObject
do {
decodedJson = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers)
}
catch (let e) {
//Error in parsing
print(e)
}
这将返回一个包含响应JSON的所有键/值对的Dictionary。您只需使用此字典即可获得所需密钥的值。
但是,更好的方法是为响应创建一个模型类。
在你的情况下,它可能是这样的:
class ResponseModel {
var success : Bool?
var accessToken : String?
var accessLevel : Int?
init(dictionary : NSDictionary) {
if let successValue = dictionary["success"] as? Bool {
success = successValue
}
if let accessTokenValue = dictionary["access_token"] as? String{
accessToken = accessTokenValue
}
if let accessTokenValue = dictionary["access_level"] as? Int{
accessLevel = accessTokenValue
}
}
}
然后,您可以更新代码以创建ResponseModel
对象:
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
//JSON serialization
var decodedJsonResponse : NSDictionary?
do {
decodedJsonResponse = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
}
catch (let e) {
//Error in parsing
print(e)
}
//Use JSON response dictionary to initialize the model object
if let decodedJson = decodedJsonResponse?["response"] as? NSDictionary {
let responseObject = ResponseModel(dictionary: decodedJson)
//use responseObject as required
print(responseObject)
}
}