首页 > 解决方案 > 无法在 swift 中将枚举从 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"
    }
}

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

标签: swiftenumsdecode

解决方案


JSON一定是这样的

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

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

从这个字符串枚举应该是MageMarksman..等等

但是您已将它们添加为

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

在枚举中,原始值被隐式赋值为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"

推荐阅读