在数组中将数组解析为swift 4中的某些数组?
问题描述:
我用解析的儿子在我的代码的消息API在数组中将数组解析为swift 4中的某些数组?
的儿子是这样的
> {
"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",
},
]
}
一些事情,你每个阵列中所看到的,我们有标题 - 说明和更多 我要分析此杰森到例如分离阵列追加所有的标题在一个阵列并追加所有描述的另一者多
这里是我的代码
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“预计字典解码,但发现一个数组来代替。”:无))
答
首先,属性/方法名称和类型名称来区分,尝试按照夫特命名约定:(以下是从Swift API Design guidelines)
Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.
另外,您的articles
结构仅表示一篇文章的数据,而不是多个。因此,它应该有一个大写字母A开始,并且是单数:
struct Article: Decodable {
其次,如果你再看看你得到回JSON,文章是字典的数组:
-"articles": [
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
...
},
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
...
},
因此,Response
结构中的articles
属性应该是Article
的数组。
struct Response : Decodable {
let articles: [Article]
}
这对我很有用,非常感谢 –