gpt4 book ai didi

json - 使用 Alamofire 快速写入 JSON 中的顶级类型无效

转载 作者:行者123 更新时间:2023-11-30 10:46:05 25 4
gpt4 key购买 nike

我有一个像这样打印的字符串

    ["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

关于json - 使用 Alamofire 快速写入 JSON 中的顶级类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com