Hello,
I asked this question on 9th March but was asked to provide a project file and can't edit the original post. Please find the original question below and please find the new test project file at https://we.tl/t-fqAu8FrgUw.
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 the catch error "Error in JSON parsing"
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(newsFeed)
print(error)
}
catch{
print("Error in JSON parsing")
}
}
}
// 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 overallrecsit: String
var dlastupd: String
var doverallrecsit: String
}
Please do you know why the parsing may be failing? Is it significant that in the debugging window the JSON is displaying backslashes before the quotation marks?
Thank you for any pointers :-)
This is one of the items in your JSON data:
"id":"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w",
"name":"Test name 0",
"country":"Test country 0",
"type":"Test type 0",
"situation":"Test situation 0",
"timestamp":"1546848000"
If you're decoding into your NewsFeed
struct then the JSON needs to match that struct.
Here's your struct:
var id: String // Yep, this is fine
var name: String // Fine
var country: String // Fine
var type: String // Fine
var overallrecsit: String // What's this? I'm expecting 'situation'...
var dlastupd: String // What's this? `timestamp`, maybe?
var doverallrecsit: String // No idea
How can you expect to decode some JSON into a struct that doesn't match it?