我有一个使用BODY参数的api,像这样
{"answers":[{"qid":2588,"value":["Free Society"]},{"qid":150,"value":["Closing of fSociety"]}],"uniqid":"t4815694"}
所以我要做的是,创建了一个名为SubmitAnswerModel
的数据模型,其中包含另一个名为QuestionAnswersToSubmit
的数据模型
import Foundation
import ObjectMapper
import RealmSwift
class SubmitAnswerModel: Object {
var answers = [QuestionAnswersToSubmit]()
@objc dynamic var uniqid: String?
override static func primaryKey() -> String {
return "uniqid"
}
}
class QuestionAnswersToSubmit: Object {
@objc dynamic var qid = 0
var value = [String]()
override static func primaryKey() -> String {
return "qid"
}
}
因此,该对象扩展了RealmObject
,现在我需要为此对象设置值并将其作为api中的BODY参数发送。我就是这样
func submitAnswerToApi() {
guard let token = UserDefault().getLoginAccessTokenKey() else {
print("No login token. Please relogin.")
return
}
let answersToSubmit = SubmitAnswerModel() //main model
let realm = try! Realm()
let savedExamResponse = realm.object(ofType: SavedExamResponse.self, forPrimaryKey: id)
answersToSubmit.uniqid = savedExamResponse?.uniqueId
var answerListToSubmit = [QuestionAnswersToSubmit]()
for item in (savedExamResponse?.questionAnswerList)! {
let answerToSubmit = QuestionAnswersToSubmit()
answerToSubmit.qid = item.questionId
answerToSubmit.value = [item.selectedOption]
answerListToSubmit.append(answerToSubmit)
}
answersToSubmit.answers = answerListToSubmit
let urlString = UrlCollection.submitAnswerUrl + "uniqid=" + answersToSubmit.uniqid! + "&token=" + token
let param = answersToSubmit
let uniqidParam = answersToSubmit.uniqid
dump(param)
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if (!JSONSerialization.isValidJSONObject(answersToSubmit)) {
print("is not a valid json object")
//return
}
request.httpBody = try? JSONSerialization.data(withJSONObject: answersToSubmit)
Alamofire.request(request)
.responseJSON { response in
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}
}
所以现在的问题是,我收到此错误Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
。在SWIFT中传递BODY参数的正确方法是什么。任何帮助,将不胜感激。谢谢!
答案 0 :(得分:0)
您的Json格式可能有误,请参考以下问题: Invalid top-level type in JSON write'
顺便说一句,使用Alamofire
设置主体的首选方法是将Dictionary
传递给参数,然后将编码设置为URLEncoding.httpbody
,如下所示:
let parameters: Parameters = ["foo": "bar"]
Alamofire.request("https://someapi/post", parameters: parameters, encoding: URLEncoding.httpbody)