Codable 函数有什么问题?
Whats wrong with Codable function?
以下是我的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")
}
我的代码有什么问题?
问题出在模型上。用这个。
// 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,它会为您生成正确的模型。
以下是我的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")
}
我的代码有什么问题?
问题出在模型上。用这个。
// 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,它会为您生成正确的模型。