简体   繁体   English

在Alamofire中的swift中发送JET请求中的json对象

[英]Sending json object in GET request in swift in Alamofire

I'm trying to execute a GET requst with json object binded to it , This i how i generated JSON object 我正在尝试用绑定到它的json对象执行GET请求,这是我如何生成JSON对象

   let jsonObject: [String: AnyObject] = [

        "ean_code": [
            "type": "match",
            "value": "16743799"
        ]
    ]

and then I executed the request 然后我执行了请求

like this 像这样

        Alamofire.request(.GET,Constant.WebClient.WS_URL + "/product?filters="+String(jsonObject),parameters:parameters)

but this gave me an error which is canot bind the URL with invalid character 但这给了我一个错误,这是一个canot绑定无效字符的URL

so i encoded the URL from this 所以我编码了这个URL

let request = String(jsonObject).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPasswordAllowedCharacterSet())!

this will encode the URL but i again this will give me following error 这将编码URL但我再次这将给我以下错误

Request failed with error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." 请求失败并显示错误:错误域= NSCocoaErrorDomain代码= 3840“字符0周围的值无效” UserInfo={NSDebugDescription=Invalid value around character 0.} UserInfo = {NSDebugDescription =字符0周围的值无效}

so my question is how can I bind a json object to GET URL?? 所以我的问题是如何将json对象绑定到GET URL?

Do something like this 做这样的事情

let parameters: [String: AnyObject] = [

    "filters": "merchantName",
    "ean_code": [
        "type": "match",
        "value": "16743799"
    ]
]

do {
    let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
    let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
    let urlEncodedJson = jsonString!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    let urlString = "http://www.filter.com/&params=\(urlEncodedJson!)"
    let url = NSURL(string: urlString)
    // Trigger alaomofire request with url
}
catch let JSONError as NSError {
    print("\(JSONError)")
}

Try: 尝试:

func encode(json: [String: AnyObject]) -> NSMutableURLRequest {
    let request: NSMutableURLRequest = ...
    if let URLComponents = NSURLComponents(URL: request.URL!, resolvingAgainstBaseURL: false) {
    let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(json)
    URLComponents.percentEncodedQuery = percentEncodedQuery
    request.URL = URLComponents.URL
    return request
}

func query(parameters: [String: AnyObject]?) -> String {
    guard let parameters = parameters else {
        return ""
    }
    var components: [(String, String)] = []

    for key in parameters.keys.sort(<) {
        let value = parameters[key]!
        components += queryComponents(key, value)
    }

    return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}

func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
    var components: [(String, String)] = []

    if let dictionary = value as? [String: AnyObject] {
        for (nestedKey, value) in dictionary {
            components += queryComponents("\(key)[\(nestedKey)]", value)
        }
    } else if let array = value as? [AnyObject] {
        for value in array {
            components += queryComponents("\(key)[]", value)
        }
    } else {
        components.append((key, "\(value)"))
    }

    return components
}

Use it as: 用它作为:

Alamofire.request(encode(json))

It is just code snipets, so you will have to place it in proper place :) 这只是代码snipets,所以你必须把它放在适当的地方:)

It looks like you are trying to add query parameters in two ways: 您似乎尝试以两种方式添加查询参数:

  • Adding a parameter to the end of you URL string 将参数添加到URL字符串的末尾
  • By passing parameters into the Alamofire request 通过将参数传递给Alamofire请求

As you are doing a GET request, your parameters should all be URL encoded anyway, as GET requests shouldn't have a body. 当您正在执行GET请求时,您的参数应该都是URL编码,因为GET请求不应该有正文。 Why don't you just add your filters query into the parameters? 为什么不直接将filters查询添加到参数中?

let parameters: [String: AnyObject] = [

    "ean_code": [
        "type": "match",
        "value": "16743799"
    ]
]

Alamofire.request(.GET, Constant.WebClient.WS_URL + "/product", parameters: parameters)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM