【问题标题】:How to decode a dictionary with a nested array inside?如何解码带有嵌套数组的字典?
【发布时间】:2021-10-01 09:09:58
【问题描述】:

我正在从端点获取一些数据,响应如下所示:

{
    "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]'

【问题讨论】:

  • 解码很好,我只是不知道如何将我的 api 的响应放入 @Published 变量中。 DispatchQueue.main.async {self.searchResults = response} searchResults 字典应该是这样说的
  • 一个叫'Verse'的人在哪里?
  • Swift 3+ 中的 JSON 值永远不会是 AnyObject(引用类型),而是 AnyJSONDecoder 将 JSON 解码为 structs。这就是错误所说的。如果您想要字典,请使用JSONSerialization
  • Swift 如何知道用var searchResults: [Verse] = [] 解码什么?它会假设我想解码results 数组吗?

标签: swift swift-dictionary swift-structs


【解决方案1】:

将 searchResults 的类型从 [String: AnyObject] 更改为 'SearchResults'

var searchResults : SearchResults?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2022-01-24
    • 2015-04-11
    • 2021-12-22
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多