Skip to content

Commit

Permalink
Merge pull request Moya#1343 from pietrocaselani/UpdateParameterEncod…
Browse files Browse the repository at this point in the history
…ingExample

Add custom parameter encoding example.
  • Loading branch information
BasThomas authored Oct 7, 2017
2 parents 8789f8f + 0f64096 commit f246ce2
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/Examples/ParameterEncoding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Use a custom ParameterEncoding
Moya is using dictionary as a root container for JSON data. But sometimes you will need to send JSON array as a root element instead. Here is solution by writing your own parameter encoding:

Define a struct or class:
```swift
import Alamofire

struct JSONArrayEncoding: ParameterEncoding {
static let `default` = JSONArrayEncoding()

func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()

guard let json = parameters?["jsonArray"] else {
return request
}

let data = try JSONSerialization.data(withJSONObject: json, options: [])

if request.value(forHTTPHeaderField: "Content-Type") == nil {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}

request.httpBody = data

return request
}
}
```

Configure the target:

```swift
public var task: Task {
switch self {
case .api:
return .requestParameters(parameters: ["jsonArray": ["Yes", "What", "abc"]], encoding: JSONArrayEncoding.default)
}
}
```

This will send data as a JSON array `["Yes", "What", "Abc"]` for the `.api` endpoint. For more information, see discussion in: [#467](https://github.com/Moya/Moya/issues/467)

0 comments on commit f246ce2

Please sign in to comment.