Swift中的JSON解码问题(数据丢失)

时间:2017-09-30 01:12:21

标签: json swift rest swift4

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

我使用Postman来验证是否正在返回JSON,以及构建JSON数据结构。

这是解码JSON的常见错误还是网络请求?或者我错过了使用NASA API的东西?

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.

以下是上述日志声明的打印输出......

library(dplyr)

id <- as.character(1:6)
first <- c("jeff", "jimmy", "andrew", "taj", "karl-anthony", "jamal")
last <- c("teague", "butler", "wiggins", "gibson", "towns", "crawford")
set.seed(1839)
a <- c(1:4, NA, NA)
b <- c(1:4, NA, NA)
c <- c(11:13, NA, 14, NA)
d <- c(11:13, NA, 14, NA)
e <- c(21, 22, NA, 24, NA, 26)
f <- c(21, 22, NA, 24, NA, 26)

1 个答案:

答案 0 :(得分: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)
}