数据映射问题
Posted
技术标签:
【中文标题】数据映射问题【英文标题】:Data Mapping Issue 【发布时间】:2021-04-02 01:47:09 【问题描述】:我正在尝试将数据从 API 映射到我的自定义类,但我在控制台中收到此错误“typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected解码数组,但找到了字典。”,基础错误:无)。不知道为什么它在那里显示这个数组;我该如何解决这个问题。错误
struct News: Codable
var status: String?
var totalResults: Int?
var articles: [Article]?
enum CodingKeys: String, CodingKey
case status = "status"
case totalResults = "totalResults"
case articles = "articles"
// MARK: - Article
struct Article: Codable
var source: Source?
var author: String?
var title: String?
var articleDescription: String?
var url: String?
var urlToImage: String?
var publishedAt: String?
var content: String?
enum CodingKeys: String, CodingKey
case source = "source"
case author = "author"
case title = "title"
case articleDescription = "description"
case url = "url"
case urlToImage = "urlToImage"
case publishedAt = "publishedAt"
case content = "content"
func getAllCountryNameFrom()
AF.request(self.baseURL + self.apiKeyPathCompononent, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil, interceptor: nil).response (responseData) in
guard let data = responseData.data else return
do
let news = try self.jsonDecoder.decode(News.self, from: data)
print(news)
catch
print(error)
【问题讨论】:
将您的data
附加为.utf8
字符串。
【参考方案1】:
-
试试这个网站/工具,https://app.quicktype.io/,它会生成一个
来自您的架构的模型
您可以使用https://proxyman.io/ 来跟踪您的响应 JSON
【讨论】:
以上是关于数据映射问题的主要内容,如果未能解决你的问题,请参考以下文章