【发布时间】:2020-04-17 01:54:19
【问题描述】:
{
"AAPL" : {
"quote": {...},
"news": [...],
"chart": [...]
},
"FB" : {
"quote": {...},
"news": [...],
"chart": [...]
},
}
您将如何快速解码。股票会发生变化,但基础报价、新闻和图表保持不变。还要提到这个 json 的股票可能有 500 长,排序顺序未知。
对于报价中的信息,它看起来像:
{
"calculationPrice": "tops",
"open": 154,
ect...
}
内幕消息:
[
{
"datetime": 1545215400000,
"headline": "Voice Search Technology Creates A New Paradigm For
Marketers",
ect...
}
]
内部图表:
[
{
"date": "2017-04-03",
"open": 143.1192,
ect...
}
]
我一直在尝试的是类似这样的例子......
Json 响应:
{
"kolsh" : {
"description" : "First only brewed in Köln, Germany, now many American brewpubs..."
},
"stout" : {
"description" : "As mysterious as they look, stouts are typically dark brown to pitch black in color..."
}
}
可编码的结构/模型:
struct BeerStyles : Codable {
struct BeerStyleKey : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
static let description = BeerStyleKey(stringValue: "description")!
}
struct BeerStyle : Codable {
let name: String
let description: String
}
let beerStyles : [BeerStyle]
}
解码器:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: BeerStyleKey.self)
var styles: [BeerStyle] = []
for key in container.allKeys {
let nested = try container.nestedContainer(keyedBy: BeerStyleKey.self,
forKey: key)
let description = try nested.decode(String.self,
forKey: .description)
styles.append(BeerStyle(name: key.stringValue,
description: description))
}
self.beerStyles = styles
}
这个例子来自https://benscheirman.com/2017/06/swift-json/,我正在尝试将它应用到我的 json 结构中。
【问题讨论】:
-
一个好的堆栈溢出问题不仅需要您想要完成的内容,还需要您已经尝试过的内容。欲了解更多信息,请参阅How to ask a good question?
-
类似于 json?["AAPL"]["quote"] 的东西。和 json?["AAPL"][1]["chart"]
-
报价、新闻和图表的内容是什么?