我正在尝试对字符串数组进行解码,其中返回的JSON中是字符串数组,但还包含嵌套数组
IE: 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:“预期对String进行解码,但找到一个数组。”, 底层错误:nil))
我知道这是因为解码器期望一个带有字符串数组的字符串
我想知道是否也可以告诉它期望多个嵌套的字符串数组。
谢谢
答案 0 :(得分:3)
您只需要创建适当的结构并将其传递给解码器即可:
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)
}
答案 1 :(得分:1)
如果您不想创建结构(例如仅需要一条数据),则可以考虑使用这种方法。
let jsonData = """
{ "people": ["Alice", "Bob"],
"departments": [["Accounts", "Sales"]],
"stores": [["Atlanta", "Denver"]]
}
""".data(using: .utf8)
if let jsonObject = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String: Any] {
if let people = jsonObject?["people"] as? [String] {
print(people)
}
if let departments = jsonObject?["departments"] as? [[String]] {
print(departments)
}
}