2016-04-26 97 views
-3
{"response":{"success":true,"access_token":"z5zbXVfaD4xOyTCLOwLIBPvuEYw7lQCUWb5U7l4KpCyXvbJkHv2jkyOZwk6RbJM7VS12d5NDImBeykygPBAa9o9FJgxUZk1Uc2Xp","access_level":"1"}} 

如何分別解析響應?我想要將每個對象都放在單獨的變量中。我的代碼:如何在Swift中解析以下JSON?

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

您是否製作任何模型類或分析邏輯是什麼? – UditS

+0

沒有。如何解析來自「responseData」的數據? – Rashed

回答

1

對於簡單的JSON解析您可以使用NSJSONSerialization

var decodedJson : AnyObject 
do { 
    decodedJson = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) 
} 
catch (let e) { 
    //Error in parsing 
    print(e) 
} 

這將返回一個字典的響應JSON的所有鍵/值對。你可以簡單地使用這個字典來獲得所需密鑰的價值。

但是,更好的方法是創建響應的模型類。

你的情況可能是這樣的:

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) 
    } 
} 
+0

你也可以查看[SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON),它在Swift中很好地處理了JSON序列化。 – UditS