如何在Swift 3中从webservice创建Json响应的模型类

时间:2017-12-21 07:28:51

标签: ios json swift web-services models

我是swift的新手。我正在研究快速项目。我收到服务器响应的响应,如下所示

kNetworkManager.executePostRequest(urlString: kAppSocialLoginURL, params:mainDictionary, requestVC: self,completionHandler: {(responseObject) -> () in
         //   print("response object:\(responseObject!)")
            if responseObject != nil {
                let responseDictionary = responseObject as! NSDictionary
                if responseDictionary is NSDictionary{
                    let obj  =  responseDictionary.value(forKey:"user")
                    if obj is NSDictionary{ //success case
                        print("NSDictionary is",obj ?? NSDictionary())
                        UtilityClass.sharedInstance.userDetailsDictionary = responseDictionary as! [String : AnyObject]
                        if let obj = responseDictionary.value(forKey:"user") as? NSDictionary {
                            if let sessionId = obj["token"] as? String {
                                UtilityClass.sharedInstance.kSessionIDString = sessionId
                            }
                            if let userObj = obj["user"] as? NSDictionary {

在上面的代码中,我检查了它的字典是否多次,或者指定为字典。我在所有课上都做这种练习。所以,我想为通用逻辑创建一些模态类,并且我想在获取Webservice数据后在每个类中使用该逻辑。

我对webservice的回复如下:

user =     {
    sessid = "-qadadadad";
    "session_name" =aadadad;
    tokenData = adadadad;
    user =         {
        access = 1513647;
        created = 14822;
        data =             {
            "ckeditor_auto_lang" = t;
            "ckeditor_default" = t;
            "ckeditor_lang" = en;
            "ckeditor_show_toggle" = t;
            "ckeditor_width" = "100%";
            contact = 1;
        };

我正在使用Alamofire进行API调用。

任何人都可以帮助我,实现这一目标吗?谢谢!

2 个答案:

答案 0 :(得分:0)

由于您在kNetworkManager中使用了Alamofire,我建议您还使用AlamofireObjectMapper来消除解析响应并将其映射到模型中的麻烦:

  

Alamofire的扩展,可自动转换JSON响应   使用ObjectMapper将数据转换为swift对象。

易于集成,您可以查看其文档以熟悉如何执行此操作。

根据您提到的响应,可映射对象应类似于:

import ObjectMapper

class UserResponse: Mappable {
    var sessId: String?
    var sessionName: String?
    var tokenData: String?
    var user: User?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        sessId <- map["sessid"]
        sessionNamen <- map["session_name"]
        tokenData <- map["tokenData"]
        user <- map["user"]
    }
}

class User: Mappable {
    var access: Int?
    var created: Int?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        access <- map["day"]
        created <- map["access"]
        conditions <- map["created"]
        data <- map["data"]
    }
}

class UserData: Mappable {
    var ckEditorAutoLang: String?
    var ckEditorDefault: String?
    var ckEditorLang: String?
    var ckEditorShowToggle: String?
    var ckEditorWidth: String?
    var contact: Int?


    required init?(map: Map){

    }

    func mapping(map: Map) {
        ckEditorAutoLang <- map["ckeditor_auto_lang"]
        ckEditorDefault <- map["ckeditor_default"]
        ckEditorLang <- map["ckeditor_lang"]
        ckEditorShowToggle <- map["ckeditor_show_toggle"]
        ckEditorWidth <- map["ckeditor_width"]
        contact <- map["contact"]
    }
}

此外,如果您使用的是Swift 4,您可能需要查看Codable,这会让您的生活更轻松!

答案 1 :(得分:0)

如果您使用Alamofire。使用此常用方法

//MARK:- Public Method
/**
*  Initiates HTTPS or HTTP request over |kHTTPMethod| method and 
returns call back in success and failure block.
*
*  @param serviceName  name of the service
*  @param method       method type like Get and Post
*  @param postData     parameters
*  @param responeBlock call back in block
*/
func requestApi(serviceName: String, method: kHTTPMethod, postData: Dictionary<String, Any>, withProgressHUD showProgress: Bool, completionClosure:@escaping (_ result: Any?, _ error: Error?, _ errorType: ErrorType, _ statusCode: NSNumber?) -> ()) -> Void
{
if NetworkReachabilityManager()?.isReachable == true
{
  if showProgress
  {
    showProgressHUD()
  }

  let headers = getHeaderWithAPIName(serviceName: serviceName)

  let serviceUrl = getServiceUrl(string: serviceName)

  let params  = getPrintableParamsFromJson(postData: postData)

  print_debug(items: "Connecting to Host with URL \(kBASEURL)\(serviceName) with parameters: \(params)")
  print_debug(items: "###### \(postData) ######")

  //NSAssert Statements
  assert(method != .GET || method != .POST, "kHTTPMethod should be one of kHTTPMethodGET|kHTTPMethodPOST|kHTTPMethodPOSTMultiPart.");

  switch method
  {
  case .GET:
    Alamofire.request(serviceUrl, method: .get, parameters: postData, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler:
      { (DataResponse) in
        SVProgressHUD.dismiss()
        switch DataResponse.result
        {
        case .success(let JSON):
          print_debug_fake(items: "Success with JSON: \(JSON)")
          print_debug(items: "Success with status Code: \(String(describing: DataResponse.response?.statusCode))")
          let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
          completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        case .failure(let error):
          print_debug(items: "json error: \(error.localizedDescription)")
          if error.localizedDescription == "cancelled"
          {
            completionClosure(nil, error, .requestCancelled, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
          }
          else
          {
            completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
          }
        }
    })
  case .POST:
    Alamofire.request(serviceUrl, method: .post, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
      { (DataResponse) in
        SVProgressHUD.dismiss()
        switch DataResponse.result
        {
        case .success(let JSON):
          print_debug_fake(items: "Success with JSON: \(JSON)")
          print_debug(items: "Success with status Code: \(String(describing: DataResponse.response?.statusCode))")
          let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
          completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        case .failure(let error):
          print_debug(items: "json error: \(error.localizedDescription)")
          completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        }
    })
  case .PUT:
    Alamofire.request(serviceUrl, method: .put, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
      { (DataResponse) in
        SVProgressHUD.dismiss()
        switch DataResponse.result
        {
        case .success(let JSON):
          print_debug_fake(items: "Success with JSON: \(JSON)")
          print_debug(items: "Success with status Code: \(String(describing: DataResponse.response?.statusCode))")
          let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
          completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        case .failure(let error):
          print_debug(items: "json error: \(error.localizedDescription)")
          completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        }
    })
  case .PATCH:
    Alamofire.request(serviceUrl, method: .patch, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
      { (DataResponse) in
        SVProgressHUD.dismiss()
        switch DataResponse.result
        {
        case .success(let JSON):
          print_debug_fake(items: "Success with JSON: \(JSON)")
          print_debug(items: "Success with status Code: \(String(describing: DataResponse.response?.statusCode))")
          let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
          completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        case .failure(let error):
          print_debug(items: "json error: \(error.localizedDescription)")
          completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        }
    })
  case .DELETE:
    Alamofire.request(serviceUrl, method: .delete, parameters: postData, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler:
      { (DataResponse) in
        SVProgressHUD.dismiss()
        switch DataResponse.result
        {
        case .success(let JSON):
          print_debug_fake(items: "Success with JSON: \(JSON)")
          print_debug(items: "Success with status Code: \(String(describing: DataResponse.response?.statusCode))")
          let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
          completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        case .failure(let error):
          print_debug(items: "json error: \(error.localizedDescription)")
          completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
        }
    })
  }
}
else
{
  SVProgressHUD.dismiss()
  completionClosure(nil, nil, .noNetwork, nil)
}
}

请根据您调整此方法,因为我直接在我的网络公共类中复制此方法