无法快速将Json的Enum转换为字符串

时间:2019-06-15 02:19:32

标签: swift enums decode

我得到了错误:

  

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

当我尝试从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对象?

1 个答案:

答案 0 :(得分:1)

您的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"