【发布时间】:2021-08-25 16:29:01
【问题描述】:
我目前正在开发一个进行 API 调用并返回和解码 JSON 响应的项目。它需要访问嵌套 json 深处的信息(响应的 URL 是https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200¶meterCd=00065&siteStatus=all)。我已经想出了如何使用以下代码解码 json 的第一级/非嵌套部分:
import UIKit
struct Post: Codable {
let name: String
}
let url = URL(string: "https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200¶meterCd=00065&siteStatus=all")!
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let posts = try! JSONDecoder().decode(Post.self, from: data)
print(posts)
}
}.resume()
然后用这个输出响应(这是我想要的):
Post(name: "ns1:timeSeriesResponseType")
但是,我编写的用于解码文件嵌套部分的代码:
import UIKit
struct queryInfo: Codable {
let queryURL: String
private enum CodingKeys: String, CodingKey {
case queryURL = "queryURL"
}
}
struct Values: Codable {
let queryinfo: queryInfo
private enum CodingKeys: String, CodingKey {
case queryURL = "queryInfo"
}
}
struct Post: Codable {
let name: String
//let scope: String
let values: Values
//let globalScope: Bool //true or false
}
let url = URL(string: "https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200¶meterCd=00065&siteStatus=all")!
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let posts = try! JSONDecoder().decode(Post.self, from: data)
print(posts)
}
}.resume()
响应错误:
ParseJSON.playground:11:8: error: type 'Values' does not conform to protocol 'Decodable'
struct Values: Codable {
^
ParseJSON.playground:15:14: note: CodingKey case 'queryURL' does not match any stored properties
case queryURL = "queryInfo"
^
error: ParseJSON.playground:11:8: error: type 'Values' does not conform to protocol 'Encodable'
struct Values: Codable {
^
ParseJSON.playground:15:14: note: CodingKey case 'queryURL' does not match any stored properties
case queryURL = "queryInfo"
^
【问题讨论】:
-
在
Values,你的变量被命名为queryinfo,所以如果你想使用一个CodingKey,它必须有相同的名字。case queryURL = "queryInfo"=>case queryinfo = "queryInfo"