Alamofireで配列をパラメータやPOSTのボディに含めると、デフォルトでは以下のようにパラメータの名前の末尾に括弧が付きますが、APIの仕様によっては括弧のないフォーマットで送りたい場合があります。
foo[]=bar1&foo[]=bar2
この投稿では以下のように括弧が無いフォーマットで送る方法を紹介します。
foo=bar1&foo=bar2
解決方法
ParameterEncodingを利用して、リクエストURLに含まれる括弧の文字を置換することで解決できます。
GETの場合
let parameterEncoding = ParameterEncoding.Custom { requestConvertible, parameters in
let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
mutableRequest.URL = NSURL(string: mutableRequest.URLString.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "="))
return (mutableRequest, error)
}
Alamofire.request(.GET, "http://example.com", parameters: ["foo": ["bar1", "bar2"]], encoding: parameterEncoding)
POSTの場合
let parameterEncoding = ParameterEncoding.Custom { requestConvertible, parameters in
let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
let httpBody = NSString(data: mutableRequest.HTTPBody!, encoding: NSUTF8StringEncoding)!
mutableRequest.HTTPBody = httpBody.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "=").dataUsingEncoding(NSUTF8StringEncoding)
return (mutableRequest, error)
}
Alamofire.request(.POST, "http://example.com", parameters: ["foo": ["bar1", "bar2"]], encoding: parameterEncoding)
括弧が付く場合と付かない場合がある背景
これはRFCで配列のパラメータに対するフォーマットが定められていないからです。AlamofireのREADMEにも以下のように記載があり、Alamofireは[]
を付ける方針をとっています。
Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz).