根据 Federico Zanetello 在他的帖子Swift 4 Decodable: Beyond The Basics中的说法,如果您需要解析原语的子集(字符串、数字、布尔值等),Codable 和 Decobable 协议将可以正常工作。
在您的情况下,只需使 DealStatus 符合 Decodable (如 JeremyP 所建议)就可以解决您的问题。您可以检查 Playgrounds 创建自己的 JSON 数据并尝试解析它:
import UIKit
enum DealStatus: String, Decodable {
case PENDING = "Pending"
case ACTIVE = "Active"
case STOP = "Stop"
case DECLINED = "Declined"
case PAUSED = "Paused"
}
struct ActiveDeals: Decodable {
let keyword: String
let bookingType: String
let expiryDate: Int
let createdAt: Int?
let shopLocation: String?
let dealStatus: DealStatus
let startingDate: Int?
}
let json = """
{
"keyword": "Some keyword",
"bookingType": "A type",
"expiryDate": 123456,
"createdAt": null,
"shopLocation": null,
"dealStatus": "Declined",
"startingDate": 789456
}
""".data(using: .utf8)!
do {
let deal = try JSONDecoder().decode(ActiveDeals.self, from: json)
print(deal)
print(deal.dealStatus)
} catch {
print("error info: \(error)")
}
输出将是:
ActiveDeals(keyword: "Some keyword", bookingType: "A type", expiryDate: 123456, createdAt: nil, shopLocation: nil, dealStatus: __lldb_expr_61.DealStatus.DECLINED, startingDate: Optional(789456))
DECLINED
但是,要成为一名更好的程序员,您应该始终保持好奇心并尝试了解事物的原理,因此,如果您对如何遵守 Decodable 协议感兴趣(假设您需要自定义键、自定义错误或更复杂的数据结构),这是你可以做到的:
import UIKit
enum DealStatus: String {
case PENDING = "Pending"
case ACTIVE = "Active"
case STOP = "Stop"
case DECLINED = "Declined"
case PAUSED = "Paused"
}
struct ActiveDeals {
let keyword: String
let bookingType: String
let expiryDate: Int
let createdAt: Int?
let shopLocation: String?
let dealStatus: DealStatus
let startingDate: Int?
}
extension ActiveDeals: Decodable {
enum StructKeys: String, CodingKey {
case keyword = "keyword"
case bookingType = "booking_type"
case expiryDate = "expiry_date"
case createdAt = "created_at"
case shopLocation = "shop_location"
case dealStatus = "deal_status"
case startingDate = "starting_date"
}
enum DecodingError: Error {
case dealStatus
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StructKeys.self)
let keyword = try container.decode(String.self, forKey: .keyword)
let bookingType = try container.decode(String.self, forKey: .bookingType)
let expiryDate = try container.decode(Int.self, forKey: .expiryDate)
let createdAt = try container.decode(Int?.self, forKey: .createdAt)
let shopLocation = try container.decode(String?.self, forKey: .shopLocation)
//Get deal status as a raw string and then convert to your custom enum
let dealStatusRaw = try container.decode(String.self, forKey: .dealStatus)
guard let dealStatus = DealStatus(rawValue: dealStatusRaw) else {
throw DecodingError.dealStatus
}
let startingDate = try container.decode(Int?.self, forKey: .startingDate)
self.init(keyword: keyword, bookingType: bookingType, expiryDate: expiryDate, createdAt: createdAt, shopLocation: shopLocation, dealStatus: dealStatus, startingDate: startingDate)
}
}
let json = """
{
"keyword": "Some keyword",
"booking_type": "A type",
"expiry_date": 123456,
"created_at": null,
"shop_location": null,
"deal_status": "Declined",
"starting_date": 789456
}
""".data(using: .utf8)!
do {
let deal = try JSONDecoder().decode(ActiveDeals.self, from: json)
print(deal)
print(deal.dealStatus)
} catch {
print("error info: \(error)")
}
在这种情况下,输出仍然相同:
ActiveDeals(keyword: "Some keyword", bookingType: "A type", expiryDate: 123456, createdAt: nil, shopLocation: nil, dealStatus: __lldb_expr_67.DealStatus.DECLINED, startingDate: Optional(789456))
DECLINED