Codable Decodable JSON 从字符串到枚举
Codable Decodable JSON from String to Enum
我正在尝试使用 codable 解码 JSON。我想知道是否有一种方法可以将 return HelloModel 的 typeCustomer 的 codable 自定义为 TypeOfCustomerEnum 类型而不是 String?
示例:
{
"name": "Hello",
"lastName": "World",
"typeOfCustomer": "Student"
}
enum TypeOfCustomerEnum: String {
let Student = "Student"
let Paying = "Paying"
let NonPaying = "Nonpaying"
}
struct HelloModel: Codable {
let name: String
let lastName: String
let typeOfCustomer: TypeOfCustomerEnum // JSON for TypeOfCustomer is a String but TypeOfCustomer wanted
}
类型 TypeOfCustomerEnum
也必须符合 Codable
并且大小写(必须是大小写)应该小写并且文字字符串必须匹配 JSON 值
enum TypeOfCustomerEnum: String, Codable {
case student = "Student"
case paying = "Paying"
case nonPaying = "NonPaying"
}
struct HelloModel: Codable {
let name: String
let lastName: String
let typeOfCustomer: TypeOfCustomerEnum
}
我正在尝试使用 codable 解码 JSON。我想知道是否有一种方法可以将 return HelloModel 的 typeCustomer 的 codable 自定义为 TypeOfCustomerEnum 类型而不是 String?
示例:
{
"name": "Hello",
"lastName": "World",
"typeOfCustomer": "Student"
}
enum TypeOfCustomerEnum: String {
let Student = "Student"
let Paying = "Paying"
let NonPaying = "Nonpaying"
}
struct HelloModel: Codable {
let name: String
let lastName: String
let typeOfCustomer: TypeOfCustomerEnum // JSON for TypeOfCustomer is a String but TypeOfCustomer wanted
}
类型 TypeOfCustomerEnum
也必须符合 Codable
并且大小写(必须是大小写)应该小写并且文字字符串必须匹配 JSON 值
enum TypeOfCustomerEnum: String, Codable {
case student = "Student"
case paying = "Paying"
case nonPaying = "NonPaying"
}
struct HelloModel: Codable {
let name: String
let lastName: String
let typeOfCustomer: TypeOfCustomerEnum
}