在嵌套的字符串数组上使用 Swift 可解码
Using Swift decodable on nested arrays of strings
我正在尝试解码一个字符串数组,其中返回的 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)
}
如果您不想创建结构(例如,只需要一段数据),可以考虑以下方法。
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)
}
}
我正在尝试解码一个字符串数组,其中返回的 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)
}
如果您不想创建结构(例如,只需要一段数据),可以考虑以下方法。
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)
}
}