如何解码内部嵌套数组的字典?
How to decode a dictionary with a nested array inside?
我正在从端点获取一些数据,响应如下所示:
{
"count": 29772,
"next": null,
"previous": null,
"results": [
{
"id": 29,
"book_name": "Book title",
"book_id": 70,
"chapter_number": 1,
"verse": "Text",
"verse_number": 20,
"chapter": 96
},
{
"id": 30,
"book_name": "Book Title",
"book_id": 70,
"chapter_number": 1,
"verse": "Lorem ipsum",
"verse_number": 21,
"chapter": 96
}
]
}
结构看起来不错:
struct SearchResults: Decodable {
let count: Int
let next: String?
let previous: String?
let results: [Verse]
}
但是,如何使用嵌套数组初始化此字典?我试过类似
// here is the issue - what should the searchResults structure look like?
// to properly store the response
var searchResults: [String: AnyObject] = [String: AnyObject]()
...
let response = try JSONDecoder().decode(SearchResults.self, from: safeData)
DispatchQueue.main.async {
self.searchResults = response // error here
}
但是得到错误信息
Cannot assign value of type 'SearchResults' to type '[String : AnyObject]'
将搜索结果的类型从 [String: AnyObject] 更改为 'SearchResults'
var searchResults : SearchResults?
我正在从端点获取一些数据,响应如下所示:
{
"count": 29772,
"next": null,
"previous": null,
"results": [
{
"id": 29,
"book_name": "Book title",
"book_id": 70,
"chapter_number": 1,
"verse": "Text",
"verse_number": 20,
"chapter": 96
},
{
"id": 30,
"book_name": "Book Title",
"book_id": 70,
"chapter_number": 1,
"verse": "Lorem ipsum",
"verse_number": 21,
"chapter": 96
}
]
}
结构看起来不错:
struct SearchResults: Decodable {
let count: Int
let next: String?
let previous: String?
let results: [Verse]
}
但是,如何使用嵌套数组初始化此字典?我试过类似
// here is the issue - what should the searchResults structure look like?
// to properly store the response
var searchResults: [String: AnyObject] = [String: AnyObject]()
...
let response = try JSONDecoder().decode(SearchResults.self, from: safeData)
DispatchQueue.main.async {
self.searchResults = response // error here
}
但是得到错误信息
Cannot assign value of type 'SearchResults' to type '[String : AnyObject]'
将搜索结果的类型从 [String: AnyObject] 更改为 'SearchResults'
var searchResults : SearchResults?