我从API获取的数据返回一个对象,但是当有多个对象时,它将在同一键中返回一个数组。使用我正在使用的当前模型(结构),显示数组时解码失败。
这些结果是随机排序的,这意味着我不知道何时将对象或数组提供给我。
有没有一种方法可以创建一个模型,该模型考虑到这一事实,并且可以为值(“ String”或“ [String]”)分配正确的类型以进行转换,从而继续解码而不会出现问题?
这是返回对象的示例:
{ "firstFloor": { "room": "Single Bed" } }
这是返回数组(针对同一键)的示例:
{ "firstFloor": { "room": ["Double Bed", "Coffee Machine", "TV", "Tub"] } }
应该 能够用作上述两个样本的模型的结构示例:
struct Hotel: Codable { let firstFloor: Room struct Room: Codable { var room: String // the type has to change to either array '[String]' or object 'String' depending on the returned results } }
这是完整的游乐场文件:
import Foundation // JSON with a single object let jsonObject = """ { "firstFloor": { "room": "Single Bed" } } """.data(using: .utf8)! // JSON with an array instead of a single object let jsonArray = """ { "firstFloor": { "room": ["Double Bed", "Coffee Machine", "TV", "Tub"] } } """.data(using: .utf8)! // Models struct Hotel: Codable { let firstFloor: Room struct Room: Codable { var room: String // the type has to change to either array '[String]' or object 'String' depending on the results of the API } } // Decoding let decoder = JSONDecoder() let hotel = try decoder.decode(Hotel.self, from: jsonObject) // print(hotel)
您可以使用带有关联值的枚举(在这种情况下为字符串和数组)封装结果的歧义,例如:
enum MetadataType: Codable { case array([String]) case string(String) init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() do { self = try .array(container.decode(Array.self)) } catch DecodingError.typeMismatch { do { self = try .string(container.decode(String.self)) } catch DecodingError.typeMismatch { throw DecodingError.typeMismatch(MetadataType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type")) } } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .array(let array): try container.encode(array) case .string(let string): try container.encode(string) } } } struct Hotel: Codable { let firstFloor: Room struct Room: Codable { var room: MetadataType } }