Use Array instead of Dictionary as JSON root container(使用Array而不是Dictionary作为Json根容器)
Moya使用Dictionary作为JSON数据的根容器.但是有时候你将需要发送JSON数组作为根元素。Moya中使用.custom 编码参数
定义一个JsonArrayEncoding闭包:
var req = request.URLRequest
let JsonArrayEncodingClosure: (URLRequestConvertible, [String: Any]?) -> (URLRequest, Error?) = { request, data in
do {
let json = try JSONSerialization.data(withJSONObject: data!["jsonArray"]!, options: .prettyPrinted)
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.httpBody = json
} catch {
return (req, nil)
}
return (req, nil)
}
配置target对象
var parameters: [String: Any]? {
switch self {
case .someAPI:
return ["jsonArray": ["Yes", "What", "Abc"]]
default:
return nil
}
}
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .someAPI:
return ParameterEncoding.custom(JsonArrayEncodingClosure)
default:
return ParameterEncoding.json
}
}
对于.someAPI端点,将会把数据作为Json 数组["Yes", "What", "Abc"]发送
总结 这小节的核心:
- 在request中传递json数组数据