将responseJSON解析为ObjectMapper

时间:2019-05-29 19:55:20

标签: swift4 alamofire objectmapper

我目前正在从Android到iOS进行迁移,最好是从Java到Swift,我得到了JSON的通用响应,但无法将其用作对象并在情节提要中显示。我真的是Swift的新人,所以我被困了一段时间。

我尝试了ObjectMapper并进行JSON解码,但完全没有结果。

我声明了我在Java(Android)中使用的响应

Model.pluck(:id, :name, ...).find_in_batches(10_000) do |ary|
  CSV.open("tmp.csv", "ab") do |csv|
    csv << ary.map{|a| a.join ','}.join("\n")
  end
end

在我的Android项目中,我使用了Gson依赖项,并且能够将JSON用作对象

class ResponseObjectMapper<T,R>: Mappable where T: Mappable,R:Mappable{

var data:T?
var message:String!
var error:R?

required init?(_ map: Map) {
    self.mapping(map: map)
}

func mapping(map: Map) {
    data          <- map["data"]
    message          <- map["message"]
    error          <- map["error"]
}
}

class UserMapper :Mappable{
var email:String?
var fullName:String?
var id:CLong?
var phoneNumber:String?
var token:CLong?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    email <- map["email"]
    fullName <- map["fullName"]
    id <- map["id"]
    phoneNumber <- map["phoneNumber"]
    token <- map["token"]
    phoneNumber <- map["phoneNumber"]
}
}    

这是给我JSON的 Alamofire

class ErrorMapper:Mappable{

var message:String?
var code:Int?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    message          <- map["message"]
    code          <- map["code"]
}

}

如果我用print(response)打印响应

func login(params: [String:Any]){Alamofire.request
("http://192.168.0.192:8081/SpringBoot/user/login", method: .post, 
parameters: params,encoding: JSONEncoding.default, headers: 
headers).responseJSON {
            response in
            switch response.result {
            case .success:

                let response = Mapper<ResponseObjectMapper<UserMapper,ErrorMapper>>.map(JSONString: response.data)


                break
            case .failure(let error):

                print(error)
            }
        }
}

如果我使用这段代码,我可以得到带有键和值的结果,但是我不知道如何将其用作对象

SUCCESS: {
data =     {
    email = "vpozo@montran.com";
    fullName = "Victor Pozo";
    id = 6;
    phoneNumber = 099963212;
    token = 6;
};
error = "<null>";
message = SUCCESS;
}

控制台:

if let result = response.result.value {
                    let responseDict = result as! [String : Any]
                    print(responseDict["data"])
                }

我想在对象中使用它,例如在View Controller中使用Optional({ email = "vpozo@gmail.com"; fullName = "Victor Pozo"; id = 6; phoneNumber = 099963212; token = 6; }) ,可能我真的很困惑,尝试使用通用属性进行映射。

user.token

1 个答案:

答案 0 :(得分:0)

首先,您将需要使用Alamofire进行所有请求的网络管理器。我做了一个广义的看起来像这样的东西。您可以根据需要对其进行修改。

import Foundation
import Alamofire
import SwiftyJSON

class NetworkHandler: NSObject {

let publicURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json"
]

let privateURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json",
    "Authorization" : ""
]

enum RequestType {
    case publicURL
    case privateURL
}

func createNetworkRequestWithJSON(urlString : String , prametres : [String : Any], type : RequestType, completion:@escaping(JSON) -> Void) {

    let internetIsReachable = NetworkReachabilityManager()?.isReachable ?? false
    if !internetIsReachable {
        AlertViewManager.sharedInstance.showAlertFromWindow(title: "", message: "No internet connectivity.")
    } else {
        switch type {
        case .publicURL :
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: publicURLHeaders)
            break
        case .privateURL:
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: privateURLHeaders)
            break
        }
    }
}

func commonRequest(urlString : String, parameters : [String : Any], completion : @escaping (JSON) -> Void , headers : HTTPHeaders){

    print("urlString:"+urlString)
    print("headers:")
    print(headers)
    print("parameters:")
    print(parameters)

    let url = NSURL(string: urlString)
    var request = URLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.httpHeaders = headers
    request.timeoutInterval = 10
    let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    if let json = json {
        print("parameters:")
        print(json)
    }

    request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
    let alamoRequest = AF.request(request as URLRequestConvertible)
    alamoRequest.validate(statusCode: 200..<300)
    alamoRequest.responseJSON{ response in
        print(response.response?.statusCode as Any )
        if let status = response.response?.statusCode {
            switch(status){
            case 201:
                print("example success")
                SwiftLoader.hide()
            case 200 :
                if let json = response.value {
                    let jsonObject = JSON(json)
                    completion(jsonObject)
                }
            default:
                SwiftLoader.hide()
                print("error with response status: \(status)")
            }
        }else{
            let jsonObject = JSON()
            completion(jsonObject)
            SwiftLoader.hide()
        }
    }
}
}

此后,如果您需要发出请求,则可以使用此功能。如果需要,它将接受参数,并且在请求完成后,它将执行一个回调函数,您可以在其中处理响应。这里的响应将是SWIFTYJSON格式。

func makeNetworkRequest(){
    let networkHandler = NetworkHandler()
    var parameters : [String:String] = [:]
    parameters["email"] = usernameTextField.text
    parameters["pass"] = passwordTextField.text
    networkHandler.createNetworkRequestWithJSON(urlString: "http://192.168.0.192:8081/SpringBoot/user/login", prametres: parameters, type: .publicURL, completion: self.handleResponseForRequest)
}


func handleResponseForRequest(response: JSON){
    if let message = response["message"].string{
        if message == "SUCCESS"{

            if let email = response["data"]["email"].string{
                //Do something with email.
            }

            if let fullName = response["data"]["fullName"].string{
                //Do something with fullName.
            }

            if let id = response["data"]["id"].int{
                //Do something with id.
            }

            if let phoneNumber = response["data"]["phoneNumber"].int64{
                //Do something with phoneNumber.
            }

            if let token = response["data"]["token"].int{
                //Do something with token.
            }
        }else{
            //Error
        }
    }
}

希望这会有所帮助。让我知道您是否被卡在任何地方。