Hello,
Please see the test project at https://we.tl/t-aWAu7kk9lD
I have a json array showing in Xcode debugger (from the line "print(dataString)"):
Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]")
But my JSON decoder is throwing a catch error
Line 57, Error in JSON parsing
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
This is the code:
let urlString = "https://www.notafunnyname.com/jsonmockup.php"
let url = URL(string: urlString)
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
var dataString = String(data: data!, encoding: String.Encoding.utf8)
print(dataString)
if error == nil && data != nil {
// Parse JSON
let decoder = JSONDecoder()
do {
let newsFeed = try decoder.decode(NewsFeed.self, from: data!)
print("line 51")
print(newsFeed)
print(error)
}
catch{
print("Line 57, Error in JSON parsing")
print(error)
}
}
}
// Make the API Call
dataTask.resume()
}
And this is my Codable file NewsFeed.swift:
struct NewsFeed: Codable {
var id: String
var name: String
var country: String
var type: String
var situation: String
var timestamp: String
}
Please do you know how to resolve the typeMismatch error?