Whats wrong with Codable function?

风格不统一 提交于 2019-12-10 12:26:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!