【问题标题】:Whats wrong with Codable function?Codable 函数有什么问题?
【发布时间】:2019-09-30 13:53:32
【问题描述】:

以下是我的 JSON:

{
   "Books":[
  {
     "title":"book title",
     "Contents":[
        {
           "figure":"Clause33",
           "url":"PressureReleifValve.html",
           "type":"video"
        }
     ]
  }
]
}

结构如下:内容中可能包含多个项目。

 struct Books: Codable {
      let title: String
      let contents: [Content]
  }
 struct Content: Codable {
      let figure, url, type: String
  }

代码如下:

guard let books = try? JSONDecoder().decode(Books.self, from: jsonData2) else {
    fatalError("The JSON information has errors")
  }

我的代码有什么问题?

【问题讨论】:

  • guard let books = try? JSONDecoder() => do { let books = try JSONDecoder()... } catch { print("Error: \(error)"}。捕捉错误并阅读它们。
  • 是的,请抓住错误并用它编辑您的问题。
  • 您缺少"Books" 部分,首先是顶层的第一个键。好吧,这取决于您的整个真实代码和可重现的代码。 “内容”当键有明确的大写字母时?你添加了 CodingKeys 吗?

标签: json swift codable


【解决方案1】:

问题出在模型上。使用这个。

// MARK: - Books
struct Books: Codable {
    let books: [Book]

    enum CodingKeys: String, CodingKey {
        case books = "Books"
    }
}

// MARK: - Book
struct Book: Codable {
    let title: String
    let contents: [Content]

    enum CodingKeys: String, CodingKey {
        case title
        case contents = "Contents"
    }
}

// MARK: - Content
struct Content: Codable {
    let figure, url, type: String
}


do {
    let books = try JSONDecoder().decode(Books.self, from: jsonData)
} catch let error {
    // handle error
}

您可以在此处复制粘贴您的 JSON https://app.quicktype.io,它将为您生成正确的模型。

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2017-03-26
    相关资源
    最近更新 更多