Use Array instead of Dictionary as JSON root container(使用Array而不是Dictionary作為Json根容器)
Moya使用Dictionary作為JSON數(shù)據(jù)的根容器.但是有時候你將需要發(fā)送JSON數(shù)組作為根元素栏妖。Moya中使用.custom 編碼參數(shù)
定義一個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端點,將會把數(shù)據(jù)作為Json 數(shù)組["Yes", "What", "Abc"]發(fā)送
總結(jié) 這小節(jié)的核心:
- 在request中傳遞json數(shù)組數(shù)據(jù)