LoginSignup
10
5

More than 5 years have passed since last update.

Alamofireで配列のパラメータから括弧の文字列を取り除く方法

Last updated at Posted at 2016-06-26

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).

参考

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5