JSON Decoding Issue and it is driving me crazy
I have a sample JSON that I am trying to decode to models in my Swift. But it keeps failing and giving me error:
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"
}
]
}
Does anyone see any issue, what am I doing wrong?