问题
Following is my JSON:
{
"Books":[
{
"title":"book title",
"Contents":[
{
"figure":"Clause33",
"url":"PressureReleifValve.html",
"type":"video"
}
]
}
]
}
Here is the structure: The content might have multiple items in it.
struct Books: Codable {
let title: String
let contents: [Content]
}
struct Content: Codable {
let figure, url, type: String
}
Here is the code:
guard let books = try? JSONDecoder().decode(Books.self, from: jsonData2) else {
fatalError("The JSON information has errors")
}
Whats wrong with my code?
回答1:
The problem is in the model. Use this one.
// 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
}
You can copy paste your JSON here https://app.quicktype.io, it will generate the right model for you.
来源:https://stackoverflow.com/questions/58169372/whats-wrong-with-codable-function