我有一个相当复杂的结构进行编码,以便将其传递给我的帖子。
case .sendData(let parameters):
urlRequest = try Alamofire.JSONEncoding.default.encode(urlRequest, withJSONObject: parameters.encode())
参数不是[String:Any]类型,而是类型' QuestionnaireAnswers'这是一个结构。所以我需要创建编码功能。我尝试了下面的代码,但它失败了
struct ItemResponse {
let question: String
let answerArray: [String]
}
// MARK: Encodable
extension ItemResponse {
func encode() -> [String: Any] {
return [
"question": question,
"answerArray": answerArray
]
}
}
struct QuestionnaireAnswers{
let version: Int
var answers: [ItemResponse]
}
// MARK: Encodable
extension QuestionnaireAnswers {
func encode() -> [String: Any] {
return [
"version": version,
"answers": answers
]
}
}
最后,JSON应如下所示:
{
version: 1,
answers: [
{ question: 'dog', answerArray: ['yay'] },
{ question: 'cat', answerArray: ['< 500'] },
{ question: 'tree', answerArray: ['sorry', 'OK then','NotWorking'] },
],
}