如何解析一个JSON数据块而不是整个JSON序列 [英] How to parse one block of JSON data instead of the entire JSON sequence
问题描述
以下是用于解析JSON API的代码.该代码有效,我能够将所有JSON值解析到下面的结构中,但是我想知道如何仅解析第一个block(?)/数组并将它们存储在该结构中,以便我可以对它们执行操作.
Below is the code that am using to parse a JSON api. The code works and i am able to parse all the JSON values into the struct below but i would like to know how to parse only the first block(?)/ array and store them in the struct so that i can perform operations on them.
let jsonUrlString = "https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=5min&apikey=demo"
let urlObj = URL(string: jsonUrlString)
URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in
guard let data = data else { return }
do {
let forex = try JSONDecoder().decode(Root.self, from: data)
print(forex.timeSeriesFX5Min)
} catch {
print(error)
}
}.resume()
}
}
struct Root: Codable {
let timeSeriesFX5Min: [String:Forex]
enum CodingKeys: String, CodingKey {
case timeSeriesFX5Min = "Time Series FX (5min)"
}
}
// MARK: - TimeSeriesFX5Min
struct Forex: Codable {
let the1Open, the2High, the3Low, the4Close: String
enum CodingKeys: String, CodingKey {
case the1Open = "1. open"
case the2High = "2. high"
case the3Low = "3. low"
case the4Close = "4. close"
}
}
推荐答案
我看到了两种方法,第一种方法是更改Root结构,在此我们需要使用消息的元数据部分
I see two ways to do this, the first requires a change to the Root struct where we need to use the Meta Data part of the message
struct Root: Codable {
let metaData: [String: String]
let timeSeriesFX5Min: [String:Forex]
enum CodingKeys: String, CodingKey {
case timeSeriesFX5Min = "Time Series FX (5min)"
case metaData = "Meta Data"
}
}
然后,我们选择标记为最新报价"的项目,并使用该值在时间序列字典中查找最新的价格条目
Then we pick up the item labeled "Last Refresed" and use the value to look up the latest price entry in the time series dictionary
do {
let forex = try JSONDecoder().decode(Root.self, from: data)
print(forex.metaData)
if let latestTime = forex.metaData["4. Last Refreshed"], let latestForex = forex.timeSeriesFX5Min[latestTime] {
print(latestForex)
}
} catch {
print(error)
}
另一种选择是利用以下事实:时间戳记以可以正确排序的格式给出,因此我们不使用元数据而是对键进行排序并选择最后一项
Another option is to take advantage of the fact that the timestamps are given in such a format that they can be properly sorted so instead of using meta data we sort the keys and pick the last item
if let latestTime = forex.timeSeriesFX5Min.keys.sorted().last, let latestForex = forex.timeSeriesFX5Min[latestTime] {
print(latestForex)
}
这篇关于如何解析一个JSON数据块而不是整个JSON序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!