有谁有管理HAL类型JSON数据的流程吗?我遇到的问题是,所有数据请求都将返回一个容器,该容器将它的实际类型嵌入到"_embedded“键中。我很难弄清楚如何解码出这种类型,因为每个嵌入式密钥都可能有多个分配给它的HalTypes。例如,如果我请求菜单项或菜单类别,它将返回相同的总体结构。下面的JSON用于菜单类别。
例如,
模型
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let category = try? newJSONDecoder().decode(Category.self, from: jsonData)
import Foundation
// MARK: - Category
struct Category: Codable {
var embedded: Embedded?
var links: CategoryLinksClass?
var count, limit: Int?
enum CodingKeys: String, CodingKey {
case embedded = "_embedded"
case links = "_links"
case count, limit
}
}
// MARK: - Embedded
struct Embedded: Codable {
var categories: [CategoryElement]?
}
// MARK: - CategoryElement
struct CategoryElement: Codable {
var links: CategoryLinks?
var id: String?
var level: Int?
var name, posid: String?
enum CodingKeys: String, CodingKey {
case links = "_links"
case id, level, name
case posid = "pos_id"
}
}
// MARK: - CategoryLinks
struct CategoryLinks: Codable {
var linksSelf: Next?
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
}
}
// MARK: - Next
struct Next: Codable {
var href: String?
var type: String?
}
// MARK: - CategoryLinksClass
struct CategoryLinksClass: Codable {
var next, linksSelf: Next?
enum CodingKeys: String, CodingKey {
case next
case linksSelf = "self"
}
}JSON
{
"_embedded": {
"categories": [
{
"_links": {
"self": {
"href": "https://api.omnivore.io/1.0/locations/iE7e78GT/menu/categories/1001/",
"type": "application/json; name=menu_category"
}
},
"id": "1001",
"level": 0,
"name": "Entree",
"pos_id": "1001"
},
{
"_links": {
"self": {
"href": "https://api.omnivore.io/1.0/locations/iE7e78GT/menu/categories/1002/",
"type": "application/json; name=menu_category"
}
},
"id": "1002",
"level": 0,
"name": "Appetizer",
"pos_id": "1002"
}
]
},
"_links": {
"next": {
"href": "https://api.omnivore.io/1.0/locations/iE7e78GT/menu/categories/?limit=2&start=2",
"type": "application/json; name=menu_category_list"
},
"self": {
"href": "https://api.omnivore.io/1.0/locations/iE7e78GT/menu/categories/?limit=2",
"type": "application/json; name=menu_category_list"
}
},
"count": 2,
"limit": 2
}发布于 2020-07-28 14:36:31
每次都可以让_embedded键接受一般的Codable结构,而不是特定的类型。
struct Category<T: Codable>: Codable {
var embedded: T?
var links: CategoryLinksClass?
var count, limit: Int?
enum CodingKeys: String, CodingKey {
case embedded = "_embedded"
case links = "_links"
case count, limit
}
}并创建为"_embedded"键返回的不同模型。
struct Embedded: Codable { ... }
struct Menu: Codable { ... }然后在解码时提供模型类型如下:
do { let decoded = JSONDecoder().decode(Category<Embedded>.self, from: data)
} catch { print(error) }https://stackoverflow.com/questions/63136550
复制相似问题