swift - 无法在 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 对象?
解决方案
你JSON
一定是这样的
let jsonString = """
{
"id" :"asda",
"key" : "key asd",
"tags" : [
"Mage",
"Marksman"
]
}
"""
注意:我在let info : Info
这里忽略。
从这个字符串枚举应该是Mage
,Marksman
..等等
但是您已将它们添加为
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"
推荐阅读
- angular - Angular 8:如何使用 Multi-Content-Projection / Multiple-Transclusion 插槽两次?
- reactjs - 如何将 React 添加到现有的 Electron 应用程序中?
- microsoft-graph-api - OneDrive - 使用 Graph API 上传文件偶尔会导致 416
- google-apps-script - 带有 onEdit Google 表格的用户/电子邮件戳
- python - 从嵌套的 xml 文件创建熊猫数据框时单行重复
- javascript - GraphQL 查询 - 如何在不同类型上重用内联片段字段
- spring - 从另一个 gradle 任务运行 gradle test
- python - 使用 python 的多处理并行化 keras 中的模型预测
- javascript - 如何将这两个数组合并为一个
- flutter - 在 CustomDialog 中捕捉按钮按下