我有一个像这样打印的字符串
["answers": <__NSArrayI 0x7fb0bce08550>(
{
qid = 884;
value = (
fSociety
);
}
)
, "uniqid": t-26963212]
我正在使用像这样的编码器将NSObject转换为Json
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)! {
var answerToSubmit = QuestionAnswersToSubmit()
answerToSubmit.qid = item.questionId
answerToSubmit.value.append(item.selectedOption)
answerListToSubmit.append(answerToSubmit)
}
let answersToSubmit = SubmitAnswerModel(answers:answerListToSubmit,uniqid:savedExamResponse?.uniqueId)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try? encoder.encode(answersToSubmit)
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [String:AnyObject]
{
print(jsonObj) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
我需要在我的API中发送BODY参数,所以每当我尝试发送这个值时,我都会得到Invalid top-level type in JSON write'
。我正在使用这样的Alamofire
let urlString = UrlCollection.submitAnswerUrl + "uniqid=" + answersToSubmit.uniqid! + "&token=" + token
var objectDictionaries = [NSDictionary]()
let allObjects = answersToSubmit
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
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)
}
}
我无法弄清楚究竟是什么错误。是因为JSON格式不正确,如果那样,我应该如何使其正确。任何帮助将深表感谢。谢谢
我在代码中发现了问题
request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
而不是序列化已编码的值,我将该值传递给request.httpBody
,如下所示:request.httpBody = data