当我尝试从字典创建json时,我得到一个错误的格式用分号而不是用于json的逗号
let jsonData = try? JSONSerialization.data(withJSONObject: params)
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";
}
答案 0 :(得分:0)
这条线解决了我的问题:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
答案 1 :(得分:-1)
let dic = ["2": "B", "1": "A", "3": "C"]
do {
//Convert to Data
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.prettyPrinted)
//Convert back to string. Usually only do this for debugging
// just get Json string
if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
print(JSONString)
}
} catch {
print(error.localizedDescription)
}