swift - 在嵌套的字符串数组上使用 Swift 可解码
问题描述
我正在尝试解码一个字符串数组,其中返回的 JSON 是一个字符串数组,但也包含嵌套数组
喜欢:
{ "people": ["Alice", "Bob"],
"departments": [["Accounts", "Sales"]]
}
我的斯威夫特代码:
let decoder = JSONDecoder()
let model = try decoder.decode([String:[String]].self, from: dataResponse)
print(model as Any)
我希望能够解码部门,但每次我这样做时都会抱怨:
错误 typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_DictionaryCodingKey(stringValue: "departments", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "预期解码字符串,但找到了一个数组。”,基础错误:无))
我知道这是因为解码器需要一个带有字符串数组的字符串
我想知道我是否也可以告诉它期望多个嵌套的字符串数组。
解决方案
您只需要创建适当的结构并将其传递给解码器:
struct Root: Decodable {
let people: [String]
let departments: [[String]]
}
let decoder = JSONDecoder()
do {
let model = try decoder.decode(Root.self, from: dataResponse)
print(model.people) // ["Alice", "Bob"]\n"
print(model.departments) // [["Accounts", "Sales"]]\n"
} catch {
print(error)
}
推荐阅读
- c++ - C++ read a Registry entry in SOFTWARE\WOW6432 from a 64-bit app
- php - 在 PHP 中创建动态数组键结构
- python - 在 Pandas 的正则表达式匹配开始时添加一个字符
- javascript - AG GRID - 使用分页和无限模型获取当前页面上的行
- python-3.x - Kivy 绑定动态按钮事件 - 始终只返回最后一项值
- javascript - 如何从 ReactJS 中的 api 响应返回的字符串字段中排除几个单词
- python - 在 tkinter 中使用阿拉伯语文本
- android - 尝试在片段中制作微调器并出现错误,您可以提出建议
- scala - 将方法和参数传递给 Scala 案例类?
- gulp - 使用 gulp、“package-solution”子任务打包 SharePoint 应用程序时出错