【发布时间】:2017-10-15 12:31:40
【问题描述】:
我在我的新闻 api 代码中使用了解析子
儿子是这样的
> {
"status": "ok",
"source": "associated-press",
"sortBy": "top",
-"articles": [
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
"title": "Pro-Trump states most affected by his health care decision",
"description": "President Donald Trump's decision to end a provision of the Affordable Care Act that was benefiting roughly 6 million Americans helps fulfill a campaign promise",
"url": "https:urlexample",
"urlToImage": "url example",
},
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
"title": "Pro-Trump states most affected by his health care decision",
"description": "President Donald Trump's decision to end a provision of the Affordable Care Act that was benefiting roughly 6 million Americans helps fulfill a campaign promise",
"url": "https:urlexample",
"urlToImage": "url example",
},
]
}
正如您在每个数组中看到的,我们有标题 - 描述等 我想将此 jason 解析为单独的数组,例如将所有标题附加到一个数组中,并将所有描述附加到另一个数组中等等
这是我的代码
struct Response : Decodable {
let articles: articles
}
struct articles: Decodable {
let title: String
let description : String
let url : String
let urlToImage : String
}
这里是json的代码
let jsonUrl = "https://newsapi.org/[your codes]"
guard let url = URL(string : jsonUrl) else {
return
}
URLSession.shared.dataTask(with: url) { (data , response , error) in
guard let data = data else {return}
do {
let article = try JSONDecoder().decode(Response.self , from : data)
print(article.articles.title)
print(article.articles.description)
print(article.articles.url)
print(article.articles.urlToImage)
}
catch {
print(error)
}
}.resume()
当我运行它时,我会收到这个错误
“本应解码字典,但找到了一个数组。”,underlyingError: nil))
【问题讨论】:
标签: ios arrays json swift swift4