![](/img/trans.png)
[英]How to decode nested JSON array and object with JSONDecoder in swift 4.1 and xcode 9.3?
[英]How to decode a nested JSON object in an array in an object?
我需要在嵌套的 JSON 深處檢索數據,但這樣做有很多麻煩。 有問題的文件可以在https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200¶meterCd=00065&siteStatus=all 找到。
// MARK: - Post
struct Post: Codable {
let name, declaredType, scope: String?
let value: PostValue?
let postNil, globalScope, typeSubstituted: Bool?
enum CodingKeys: String, CodingKey {
case name, declaredType, scope, value
case postNil
case globalScope, typeSubstituted
}
}
// MARK: - PostValue
struct PostValue: Codable {
let queryInfo: QueryInfo?
let timeSeries: [TimeSery]?
}
// MARK: - QueryInfo
struct QueryInfo: Codable {
let queryURL: String?
let criteria: Criteria?
let note: [Note]?
}
// MARK: - Criteria
struct Criteria: Codable {
let locationParam, variableParam: String?
let parameter: [JSONAny]?
}
// MARK: - Note
struct Note: Codable {
let value, title: String?
}
// MARK: - TimeSery
struct TimeSery: Codable {
let sourceInfo: SourceInfo?
// let variable: Variable?
// let values: [TimeSeryValue]?
let name: String?
}
// MARK: - SourceInfo
struct SourceInfo: Codable {
let siteName: String?
// let siteCode: [SiteCode]?
// let timeZoneInfo: TimeZoneInfo?
let geoLocation: GeoLocation?
let note, siteType: [JSONAny]?
// let siteProperty: [SiteProperty]?
}
// MARK: - GeoLocation
struct GeoLocation: Codable {
let geogLocation: GeogLocation?
let localSiteXY: [JSONAny]?
}
// MARK: - GeogLocation
struct GeogLocation: Codable {
let srs: String?
let latitude, longitude: Double?
}
檢索數據的代碼:
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let posts = try! JSONDecoder().decode(Post.self, from: data)
if let coord = (posts.value?.timeSeries?.sourceInfo?.geoLocation?.geogLocation?.srs) {
print(coord)
}
}
}.resume()
不幸的是,這會返回錯誤
error: ParseJSON.playground:330:89: error: type of expression is ambiguous without more context
timeSeries
被定義為[TimeSery]
,這意味着它是一個數組,但您試圖訪問它,就好像它只是一個值一樣。 由於我不確定您的意圖是什么,因此很難說確切的修復方法是什么,但一種可能性是從中訪問第first
值(相當於要求[0]
,但它返回一個 Optional):
posts.value?.timeSeries?.first?.sourceInfo?.geoLocation?.geogLocation?.srs
順便說一句,調試此問題的一種方法是將表達式分解為不太復雜的部分(我從posts.value
開始,然后添加代碼直到找到問題(在本例中為timeSeries.sourceInfo
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.