使用URLRequestConvertible协议(Alamofire)将嵌套JSON作为Request参数

时间:2017-04-20 07:46:48

标签: ios xcode swift3 alamofire

Alamofire提供了一个非常方便的协议URLRequestConvertible,我可以通过创建路由器类以更加可管理的方式管理我的REST api。

一切正常,直到我不得不用 Post方法请求REST api,其中我必须将嵌套的 JSON作为参数传递如下: -

{
    “studentID” : "297",
    “studentName” : “Jack”,
    “FilterValues” : [
      {
        “Field1” : “code”,
        “Field2” : “1234232”,
        “Field3” : “111”
      }
    ]
}

我面临的问题是,当我使用基本JSON参数进行Rest调用时,协议正常工作如下: -

{
 “field1” : "jack",
 “field2” : “1233434”,
 "field3" : "test"
}

但是当我不得不使用嵌套的JSON进行调用时,将忽略辅助JSON并将上述参数视为:

{
  “studentID” : "297",
  “studentName” : “Jack”,
  “FilterValues” : [

  ]
}

这是我的路由器类: -

class Router: URLRequestConvertible {

static let baseURL = "http://xxxxxx.com"

case login (username: String, password: String)
case studentList (studentID: String, studentName:String)

var method: HTTPMethod {
    return .post
}

var path: String {
    switch self {
    case .login:
        return "/login"
    case .studentList:
        return "/list"
    }
}


public func asURLRequest() throws -> URLRequest {

    let parameters: [String: Any] = {
        switch self {
        case .login(let username, let password):
            return ["username": username, "password": password]
        case .studentList (let studentID, let studentName):
            return ["studentID": studentID, "studentName": studentName, "FilterValuess": [["Field1": "code", "Field2": "someValue", "Field3": "someValue"]]]
        default:
            return [:]
        }
    }()

    let url = try Router.baseURL.asURL()
    var request = URLRequest(url: url.appendingPathComponent(path))
    request.httpMethod = method.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Accept")

//   request.setValue("application/json", forHTTPHeaderField: "Content-Type") Tried no success
//   request.httpBody = try! JSONSerialization.data(withJSONObject: parameters) Tried With JSONSerialization but no success.

    return try URLEncoding.default.encode(request, with: parameters as! Parameters)
 }
}

登录API工作正常。但是studentList没有成功,因为Alamofire不识别JSON参数。

整天通过谷歌搜索其解决方案,但找不到一个。 然后我尝试了Alamofire的另一个请求api如下: -

    let parameters = ["studentID": studentID, "studentName": studentName, "FilterValuess": [["Field1": "code", "Field2": "someValue", "Field3": "someValue"]]] as [String: Any]
    var request = URLRequest(url: URL(string: "http://xxxxxx.com/list")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)

    Alamofire.request(request)
        .responseString(completionHandler: { response in
            switch response.result {
            case .failure(let error):
                print(error)
                if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                    print(responseString)
                }
            case .success(let responseObject):
                // Received desired output
                print(responseObject)
            }
        })

这给出了所需的输出。但是我想用URLRequestConvertible来实现结果,因为我不想以不同的方式处理每个api。如果我的路由器类是 URLRequestConvertible 的子类处理我的所有REST API,那就太棒了。

我的问题是,有什么方法可以使用 URLRequestConvertible Alamofire 中将嵌套JSON作为参数发送?

任何帮助都非常值得赞赏。

1 个答案:

答案 0 :(得分:0)

更改最后一行

pubKey

privKey