【问题标题】:Issue with JSON decoding in Swift (data missing)Swift 中的 JSON 解码问题(数据丢失)
【发布时间】:2017-09-30 01:12:21
【问题描述】:

我正在尝试使用 Swift 4 查询 NASA 图像 API (latest docs here)。我使用 JSONPlaceholder 设置并测试了我的请求,以确保我的网络请求和解码设置正确。一切正常,但是当我切换 URL 和相应的 JSON 数据结构时,我收到一条错误消息,提示“无法读取数据,因为它丢失了。”

我已经使用 Postman 来验证是否返回了 JSON,并构建了 JSON 数据结构。

这是解码 JSON 的常见错误还是网络请求的问题?还是我在使用 NASA API 时遗漏了什么?

let NASAURL = URL(string: "https://images-api.nasa.gov/search?q=moon")
    let session = URLSession(configuration: .default)
    let task = session.dataTask(with: NASAURL!) { (rdata, response, error) in
        NSLog("Data Description: " + (rdata!.debugDescription) + "\nResponse: " + response.debugDescription + "\nError Description: " + error.debugDescription)

        guard rdata != nil else{
            NSLog("No data")
            return
        }
        guard error == nil else{
            NSLog(response.debugDescription + "\n")
            NSLog(error.debugDescription)
            NSLog(error.debugDescription)
            return
        }
        let decoder = JSONDecoder()
        do{
            NSLog(rdata.debugDescription)
            let usr = try decoder.decode(Collect.self, from: rdata!) // Throws
            NSLog(usr.href)

        } catch {
            NSLog("Error: " + error.localizedDescription)
        }
    }
    task.resume()

// Collect is in its own class/file
struct Collect: Codable {
    var href: String
    //var items: [Items]
}

以下是上述日志语句的打印输出...

2017-09-29 19:50:24.135288-0500 OpenNASA[16993:10774203] Data Description: 67669 bytes
Response: Optional(<NSHTTPURLResponse: 0x60000003db00> { URL: https://images-api.nasa.gov/search?q=moon } { status code: 200, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "public, max-age=300, s-maxage=600";
    "Content-Encoding" = gzip;
    "Content-Length" = 9334;
    "Content-Type" = "application/json; charset=UTF-8";
    Date = "Sat, 30 Sep 2017 00:48:11 GMT";
    Server = "nginx/1.4.6 (Ubuntu)";
    "Strict-Transport-Security" = "max-age=31536000";
    Vary = "Accept-Encoding";
    "access-control-allow-headers" = "Origin,Content-Type,Accept,Authorization,X-Requested-With";
    "access-control-allow-methods" = GET;
} })
Error Description: nil
2017-09-29 19:50:24.137324-0500 OpenNASA[16993:10774203] Optional(67669 bytes)
2017-09-29 19:56:01.843750-0500 OpenNASA[16993:10774203] Error: The data couldn’t be read because it is missing.

【问题讨论】:

  • 你能 pod 你的 Collect 结构吗?
  • 如果您从错误打印输出中删除.localizedDescription(改为使用"Error: \(error)"),您应该会看到更详细的错误消息。
  • 我收到了这个错误-------> keyNotFound(CodingKeys(stringValue: "user_id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "result ", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"user_id\", intValue: nil) (\"user_id\").", underlyingError: nil))

标签: json swift rest swift4


【解决方案1】:

你的 Codable 应该像下面这样:

struct Collect: Codable {
    var collection: Links
}
struct Links: Codable {
    var links: [Href]
}

struct Href: Codable {
    var href: String
}

你必须像下面这样调用:

let usr = try decoder.decode(Collect.self, from: rdata!) // Throws
let links = usr.collection.links
for link in links {
    print(link.href)
}

【讨论】:

  • 这是获取所有需要的数据吗?或者只是其中的一小部分
  • 只为href
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2018-12-25
  • 2021-08-29
相关资源
最近更新 更多