The full error is typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
I have tried both [QuoteData].self and QuoteData.self
Here is my struct
This is the JSON I am requesting
I have tried both [QuoteData].self and QuoteData.self
Code Block func parseJSON(quoteData: Data) { let decoder = JSONDecoder() do { let decodedData = try decoder.decode(QuoteData.self, from: quoteData) //print(decodedData.zero[0].content) print(decodedData.zero[0].content) } catch { print(error) } }
Here is my struct
Code Block struct QuoteData: Decodable, Equatable { private enum CodingKeys : String , CodingKey { case zero = "0" } let zero : [Zero] struct Zero: Decodable, Equatable { let content : String } }
This is the JSON I am requesting
Code Block [1 item 0: { "content":"If you are out to describe the truth, leave elegance to the tailor." "author":"Albert Einstein" "category":"truth" } ]
Code Block
Thanks. Text would always be better than image when showing JSON data.This is what I got when I added that line.
With removing escaping characters and re-formatted, your JSON looks like this:
Code Block [ { "content":"That's a great feeling to know that I'm going into a project that I have no idea what will become of that movie, but I really trust Ang Lee. And I really trusted Ron. It's just really nice to work with people that you feel that way about.", "url":"https://URL.. Connelly", "category":"trust" } ]
No 1 item, No 0:.
And what is the most important is that the outermost structure is JSON array indicated by [ and ].
You may need to pass an Array type to JSONDecoder.decode.
Something like this:
Code Block struct QuoteItem: Decodable, Equatable { let content: String //let url: URL //let category: String } func parseJSON(quoteData: Data) { //print(String(data: quoteData, encoding: .utf8) ?? "*") let decoder = JSONDecoder() do { let decodedData = try decoder.decode([QuoteItem].self, from: quoteData) //<- Pass an Array type //Here, `decodedData` is of type `[QuoteItem]` print(decodedData[0].content) } catch { print(error) } }