【发布时间】:2019-01-01 01:32:27
【问题描述】:
我有以下型号:
struct Article: Decodable {
let title: String
let description: String
let imageURL: String
private enum CodingKeys: String, CodingKey {
case title
case description
case imageURL = "urlToImage"
}
}
来自 URL 的 JSON 是这样的:
{
status: "ok",
totalResults: 70,
articles: [
{
source: {
id: null,
name: "Oilprice.com"
},
author: "Tim Daiss",
title: "$70 Oil Could Be Right Around The Corner | OilPrice.com - OilPrice.com",
description: "A recent Bloomberg survey of oil analysts suggests that many believe oil could hit $70 per barrel in 2019, but are they just downplaying the bearish signals?",
url: "https://oilprice.com/Energy/Crude-Oil/70-Oil-Could-Be-Right-Around-The-Corner.html",
urlToImage: "https://d32r1sh890xpii.cloudfront.net/article/718x300/d7b8868e80d766d6a5d401219c65d6a0.jpg",
publishedAt: "2019-01-01T00:00:08Z",
content: "Oil markets have always been cyclical, and now even more so with advanced electronic trading, more speculation (which often results in wider oil price swings) and more producers, including the resurgence of U.S. oil production, now reaching over 11 million ba… [+4696 chars]"
},
{
source: {
id: "cnbc",
name: "CNBC"
},
author: "Jordan Novet",
title: "Activision Blizzard plans to fire its CFO for an unspecified cause - CNBC",
description: "Shares of gaming company Activision Blizzard moved lower Monday after it announced plans to let go of its chief financial officer.",
url: "https://www.cnbc.com/2018/12/31/activision-blizzard-plans-to-fire-its-cfo-for-an-unspecified-cause.html",
urlToImage: "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2012/08/02/48465125-activision-200.1910x1000.jpg",
publishedAt: "2018-12-31T23:18:17Z",
content: "Activision Blizzard shares moved down 1 percent in after-hours trading on Monday after the company said that it has informed its chief financial officer, Spencer Neumann, that it plans to let him go. For now he has been placed on a paid leave of absence. div … [+950 chars]"
}
]
}
我想要的只是 articles 键中的值。如何使用 Swift 4 JSONDecoder 获取它。
我知道如何通过创建父结构然后在父结构中创建“文章”属性来做到这一点。但是如果没有父结构,我怎么能做到这一点。
【问题讨论】:
-
@impression7vx 这是旧的做事方式。我正在寻找 JSONDecoder 方式。
-
我明白了。您正在尝试解析其中的一部分而不是整个内容。有趣的。你不想要一个父结构,这样你就可以使用
totalResults和status吗? -
"来自 URL 的 JSON 是这样的" 不,不是。您显示的不是有效的 JSON。
-
单独使用 JSONDecoder,如果没有某种外部结构,您将无法解码,因为您的结果将是一个 Article 数组,它是一个外部实体。因此,仅仅定义文章是不够的。
标签: swift jsondecoder