swift - 在嵌套的字符串数组上使用 Swift decodable

标签 swift codable

我正在尝试解码一个字符串数组,其中返回的 JSON 是一个字符串数组,但也包含嵌套数组

喜欢:

{ "people": ["Alice", "Bob"], 
"departments": [["Accounts", "Sales"]]
}

我的 Swift 代码:

let decoder = JSONDecoder()
let model = try decoder.decode([String:[String]].self, from: dataResponse)
print(model as Any)

我希望能够解码部门,但每次我这样做都会提示:

Error typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_DictionaryCodingKey(stringValue: "departments", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))

我知道这是因为解码器需要一个带有字符串数组的字符串

我想知道我是否也可以告诉它期待多个嵌套的字符串数组。

最佳答案

您只需要创建适当的结构并将其传递给解码器:

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) 
}

关于swift - 在嵌套的字符串数组上使用 Swift decodable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54971424/

相关文章:

ios - 如何在 Swift 3 中将 captureStillImageAsynchronously(sampleBuffer) 转换为 base64 编码

ios - 位置权限确定器

json - 在 swift 中将 UUID() 与 json 一起使用

swift - 在函数中传递一个闭包

ios - 如何阻止背景阻止 Swift 4 中的其他元素?

swift - 如何在 Swift 中从自定义编码/解码的 json 中删除数据模型 nil 字段

ios - 无法将类型 '[[ModelName]?]' 的值转换为预期的参数类型 '[ModelName].Type'

ios - Codable 如何适应 iOS 恢复过程?

ios - Json 解码为具有动态值类/结构类型的 swift 类

ios - 为什么有些方法的首字母大写?