无法在 swift 中将 Enum 转换为 Json 中的字符串



我收到错误:

无法从无效的字符串值法师初始化角色

当我尝试将字符串数组解释为 JSON 文件中的枚举类型时。

struct ChampionsData : Decodable{
    let id : String
    let key : String
    let info : Info
    let tags : [Role]
}
enum Role : String, CaseIterable, Decodable{
    case Tank = "you believe that last person standing wins"
    case Mage = "you like fantacies and tricking people"
    case Assasin = "you enjoy living with danger"
    case Fighter = "you are the warrior that built this town"
    case Support = "you are a reliable teammate that always appears where you are needed "
    case Marksman = "you tend to be the focus of the game, or the reason of victory or loss"
    enum CodingKeys: String, CodingKey {
        case mage = "Mage"
        case assassin = "Assassin"
        case tank = "Tank"
        case fighter = "Fighter"
        case support = "Support"
        case marksman = "Marksman"
    }
}

如果我想将标签解释为角色枚举类型的数组而不是字符串数组(或摆脱错误(,如何将其解析为 JSON 对象?

你的JSON一定是这样的

let jsonString = """
{
"id" :"asda",
"key" : "key asd",
"tags" : [
       "Mage",
       "Marksman"
]
}
"""

注意:我在这里忽略了let info : Info

并且从这个字符串枚举应该是MageMarksman..依此类推

但是您已经将它们添加为

case Mage = "you like fantacies and tricking people"*

在 Enum 中,原始值隐式分配为 CodingKeys

将您的代码更新为此

enum Role : String, Decodable {
    case tank = "Tank"
    case mage = "Mage"
    case assasin = "Assassin"
    case fighter = "Fighter"
    case support = "Support"
    case marksman = "Marksman"
    var value: String {
        switch self {
        case .tank:
            return "you believe that last person standing wins"
        case .mage:
            return "you like fantacies and tricking people"
        case .assasin:
            return "you enjoy living with danger"
        case .fighter:
            return "you are the warrior that built this town"
        case .support:
            return "you are a reliable teammate that always appears where you are needed"
        case .marksman:
            return "you tend to be the focus of the game, or the reason of victory or loss"
        }
    }
}

然后你可以像这样解码后使用该值

let data = jsonString.data(using: .utf8)!
// Initializes a Response object from the JSON data at the top.
let myResponse = try! JSONDecoder().decode(ChampionsData.self, from: data)
print(myResponse.tags.first?.value as Any)

如果我们使用开头提到的 json,我们将得到

"you like fantacies and tricking people"

最新更新