Swift 4 JSON解析报错求助:法语区Swift新手未找到解决办法
Hey there! Let's get that JSON parsing working for you. I took a look at the JSON file you're trying to decode, and I see the main issue right away—your model structure doesn't match the actual JSON hierarchy.
The Root Problem
Your JSON isn't a single Station object—it's a top-level object that contains an array of stations under the key stations. Here's a snippet of what the JSON looks like:
{
"stations": [
{
"ID": 1,
"name": "Saint-Lô - Gare Routière",
"lines": "A, C"
},
// More stations here...
]
}
Trying to decode directly to Station.self will throw an error because the decoder is expecting a single station, not an object wrapping an array of stations.
Fixed Code
First, update your model structures to match the JSON:
import UIKit // This top-level struct matches the root of your JSON struct StationResponse: Decodable { let stations: [Station] } // Your original Station struct works perfectly for each item in the array struct Station: Decodable { let ID: Int let name: String let lines: String }
Then, complete your viewDidLoad with proper parsing logic (I filled in the missing URLSession code):
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let urlString = "https://celestinlebehot.com/saintlobus-export-2.json" guard let url = URL(string: urlString) else { print("Invalid URL—double-check the link!") return } URLSession.shared.dataTask(with: url) { data, response, error in // Handle network errors first if let error = error { print("Network error: \(error.localizedDescription)") return } // Make sure we actually got data back guard let data = data else { print("No data received from the server") return } do { // Decode the top-level response first, then grab the stations array let response = try JSONDecoder().decode(StationResponse.self, from: data) let stations = response.stations // Test it out by printing the first station if let firstStation = stations.first { print("Success! First station: \(firstStation.name) (ID: \(firstStation.ID))") } // Important: If you're updating UI with this data, switch back to the main thread DispatchQueue.main.async { // Add your UI update code here (e.g. populate a table view) } } catch { // Print detailed parsing errors to debug print("Parsing failed: \(error)") print("Detailed error info: \(error.localizedDescription)") } }.resume() // Don't forget to resume the data task! } }
Quick Tips to Avoid Future Issues
- Always double-check that your Swift structs match the exact structure and key names of your JSON (case sensitivity matters—
IDvsidwould break things!) - Never update UI from a background thread—always use
DispatchQueue.main.asyncfor UI changes - Print errors when decoding fails; they usually tell you exactly what's wrong (e.g. "expected dictionary but got array")
内容的提问来源于stack exchange,提问作者itinous

