【发布时间】:2018-09-16 01:42:31
【问题描述】:
我有一个非常奇怪的案例,我使用 JSON 并认为我可以将子字符串一直插入到我想要访问的数据,但是,它没有按预期工作。
使用 QuickType,我能够转换这个 JSON:https://kidsuper.fodalabs.com/wp-json/wp/v2/art
到下面。
当我尝试访问时,似乎我应该能够做到.acf.gallery.id 但是一旦我到达acf.gallery,它就会说.id 不存在。这很奇怪,但这是我尝试时返回的结果
let temp = imageArray[indexPath.row].acf.gallery.id
Value of type 'GalleryUnion?' has no member 'id'
只是为了好玩,我尝试了这个,但也没有运气:
let temp = imageArray[indexPath.row].acf.GalleryUnion.galleryElementArray
Error
:“Acf”类型的值没有成员“GalleryUnion”
我打印.acf.gallery 时的返回是这样开始的:
Acf(company: "Season #3", gallery: Optional(weddingszn.GalleryUnion.galleryElementArray([weddingszn.GalleryElement( id: 135, galleryID: 135, title: "1-791x1024", filename: "1-791x1024.jpg", url: "https://kidsuper.fodalabs.com/wp-content/up
下面是我要解析的完整代码。有任何想法吗?
struct Acf: Codable {
let company: String
let gallery: GalleryUnion?
let tagline: String
let featuredImg: Bool?
enum CodingKeys: String, CodingKey {
case company, gallery, tagline
case featuredImg = "featured_img"
}
}
enum GalleryUnion: Codable {
case bool(Bool)
case galleryElementArray([GalleryElement])
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Bool.self) {
self = .bool(x)
return
}
if let x = try? container.decode([GalleryElement].self) {
self = .galleryElementArray(x)
return
}
throw DecodingError.typeMismatch(GalleryUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for GalleryUnion"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .bool(let x):
try container.encode(x)
case .galleryElementArray(let x):
try container.encode(x)
}
}
}
struct GalleryElement: Codable {
let id, galleryID: Int
let title, filename: String
let url: String
let alt, author, description, caption: String
let name, date, modified: String
let mimeType: MIMEType
let type: TypeEnum
let icon: String
let width, height: Int
let sizes: Sizes
enum CodingKeys: String, CodingKey {
case id = "ID"
case galleryID = "id"
case title, filename, url, alt, author, description, caption, name, date, modified
case mimeType = "mime_type"
case type, icon, width, height, sizes
}
}
【问题讨论】:
-
不应该是
acf.GalleryUnion是acf. gallery? -
是的,我都试过了,结果一样
标签: ios json swift api quicktype