【发布时间】:2019-12-06 06:31:00
【问题描述】:
在浏览器中,我的网址以完美的 JSON 格式给出结果,如下所示
"articles": [
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Times Of India",
但是在 Xcode 输出中,我得到的响应如下。如何将此响应转换为完美的 json 格式
{
articles = (
{
author = "Times Of India";
content = "Hyderabad: Senior Police officials arrive at the site of the encounter. All four accused in the rape
description = "India News: All four accused in the rape and murder of woman veterinarian in Telangana have been killed in an encounter with the police. Cops claimed they tried t";
publishedAt = "2019-12-06T04:15:00Z";
source = {
name = "The Times of India";
};
},
我正在使用以下代码来解码 json 数据
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data, error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: [])
print(jsonResponse) //Response result
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
请帮我解决这个问题。
【问题讨论】:
-
你能告诉我 JSON url 吗?
-
XCode 上的响应中有一个
articles键,而浏览器响应没有。您确定在这两种情况下都使用相同的url吗? -
是的。我使用的是相同的网址,我只是删除了该部分。实际上两者都有文章键。我得到的是等号(=)而不是冒号(:)。我刚刚又改了。
-
有什么问题?第一个输出是 JSON(顺便说一下,它不是有效的 JSON),第二个输出是
print(jsonResponse)的结果,它是字典的description。
标签: ios foundation decodable