Anonymous
Проблема с декодированием JSON, и это сводит меня с ума
Сообщение
Anonymous » 28 ноя 2025, 02:56
У меня есть образец JSON, который я пытаюсь декодировать в модели в своем Swift. Но он продолжает выходить из строя и выдает ошибку:
Код: Выделить всё
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [],
debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))
struct HTTPClient {
func fetchMessages() async throws -> [MessageType: [Message]] {
let (data, _) = try await URLSession.shared.data(from: Constants.Urls.Messages)
return try JSONDecoder().decode([MessageType: [Message]].self, from: data)
}
}
enum MessageType: String, CaseIterable, Codable {
case onBudgetCreated = "onBudgetCreated"
}
struct Message: Decodable {
let title: String
let text: String
let image: URL
}
Here is the JSON I am decoding:
{
"onBudgetCreated": [
{
"title": "You Made a Budget?",
"text": "Some text.",
"image": "https://example.com/images/someimage.png"
},
{
"title": "Good work",
"text": "something here",
"image": "https://example.com/images/someimage.png"
}
]
}
Кто-нибудь замечает какие-либо проблемы, что я делаю не так?
Подробнее здесь:
https://stackoverflow.com/questions/798 ... g-me-crazy
1764287818
Anonymous
У меня есть образец JSON, который я пытаюсь декодировать в модели в своем Swift. Но он продолжает выходить из строя и выдает ошибку: [code]Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil)) struct HTTPClient { func fetchMessages() async throws -> [MessageType: [Message]] { let (data, _) = try await URLSession.shared.data(from: Constants.Urls.Messages) return try JSONDecoder().decode([MessageType: [Message]].self, from: data) } } enum MessageType: String, CaseIterable, Codable { case onBudgetCreated = "onBudgetCreated" } struct Message: Decodable { let title: String let text: String let image: URL } Here is the JSON I am decoding: { "onBudgetCreated": [ { "title": "You Made a Budget?", "text": "Some text.", "image": "https://example.com/images/someimage.png" }, { "title": "Good work", "text": "something here", "image": "https://example.com/images/someimage.png" } ] } [/code] Кто-нибудь замечает какие-либо проблемы, что я делаю не так? Подробнее здесь: [url]https://stackoverflow.com/questions/79832151/json-decoding-issue-and-it-is-driving-me-crazy[/url]