5

我在优雅地处理此错误时遇到问题debugDescription: "Expected String value but found null instead." 我知道在符合 的结构中Codable,我的存储属性需要声明为可选字符串,正如我在这篇文章中所读到的

我试过了,仍然出现错误。我在那篇文章中还读到,我还可以自定义解码器以将 nil 替换为空字符串。我不知道如何诚实地做到这一点。

这是我的代码:

struct Discover: Codable {
    var page: Int
    var totalResults: Int
    var totalPages: Int
    var results: [DiscoverResults]

     enum CodingKeys: String, CodingKey {
        case page
        case totalResults = "total_results"
        case totalPages = "total_pages"
        case results = "results"
    }

}

struct DiscoverResults {
    var title: String
    var releaseDate: String
    var posterPath: String?
    var id: Int
    var genreIds: [Int]
    var poster: UIImage?

     enum CodingKeys: String, CodingKey {
        case title
        case posterPath = "poster_path"
        case releaseDate = "release_date"
        case id
        case genreIds = "genre_ids"
    }
}

extension DiscoverResults: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        title = try values.decode(String.self, forKey: .title)
        releaseDate = try values.decode(String.self, forKey: .releaseDate)
        posterPath = try values.decode(String.self, forKey: .posterPath)
        id = try values.decode(Int.self, forKey: .id)
        genreIds = try values.decode([Int].self, forKey: .genreIds)
    }
}

extension DiscoverResults: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(posterPath, forKey: .posterPath)
        try container.encode(releaseDate, forKey: .releaseDate)
        try container.encode(id, forKey: .id)
        try container.encode(genreIds, forKey: .genreIds)
    }
}

由于我正在使用电影 api,因此某些电影的posterPathin为空。DiscoverResults如果需要 JSON 本身,我将编辑该帖子。

4

0 回答 0