gpt4 book ai didi

json - htmlBody swift 的 json 格式错误

转载 作者:行者123 更新时间:2023-11-28 09:24:53 25 4
gpt4 key购买 nike

当我尝试从字典创建 json 时,我得到一个错误的格式,用分号代替 json 的逗号

let jsonData = try? JSONSerialization.data(withJSONObject: params)

参数是字典。我尝试使用选项:.prettyPrinted 但相同

result 
{
"key": "value";
"key": "value"
}
instead of
{
"key": "value",
"key": "value"
}

我试图从一个文件中读取,但结果与分号相同:(

更新这是完整的代码:

let params: Dictionary<String, String> = ["country":"A"
,"language":"A"
,"query":"some query"
,"context": "null"]
let baseURL = "someURL"
let url = URL(string: baseURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
print(try? JSONSerialization.jsonObject(with: request.httpBody!))

} catch let error {
print(error.localizedDescription)
}

这是输出:

Optional({
context = null;
country = A;
language = A;
query = "some query";
})

可选的不是问题,而是分号

let json = try! JSONSerialization.jsonObject(with: request.httpBody!, options: .allowFragments)

输出:

{
context = null;
country = A;
language = A;
query = "some query";
}

最佳答案

这一行解决了我的问题:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

关于json - htmlBody swift 的 json 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778217/

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