Swift 4读取JSON失败,仅打印Foundation.JSONDecoder求助
Foundation.JSONDecoder) Hey there! I totally get how frustrating it is when you’re stuck on JSON parsing and all you see is Foundation.JSONDecoder printed instead of your actual data. Let’s walk through the most common fixes for this issue, using your scenario with the Artwork.swift model and your target JSON endpoint.
First: Verify Your Artwork Model Matches the JSON Structure
The JSONDecoder relies entirely on the Codable protocol to map JSON fields to your Swift model. If your model’s properties don’t align with the JSON keys or types, parsing will fail silently (or you’ll end up with unexpected output).
First, based on your endpoint’s response, here’s a snippet of the JSON structure you’re working with:
Sample JSON response snippet:
[ { "id": "1", "nom": "Parc des Buttes-Chaumont", "lat": 48.8867, "lon": 2.3842, "description": "Un grand parc avec des falaises et un lac" } ]
Your Artwork struct needs to mirror this exactly—including matching key names (or using CodingKeys if you prefer different Swift property names) and correct data types:
struct Artwork: Codable { let id: String let name: String let latitude: Double let longitude: Double let description: String // Use CodingKeys to map JSON keys to your Swift property names enum CodingKeys: String, CodingKey { case id case name = "nom" // JSON uses "nom", Swift uses "name" case latitude = "lat" case longitude = "lon" case description } }
Double-check every field: if the JSON has a string, your model can’t use an Int, and vice versa. Missing fields or mismatched names will break parsing.
Second: Fix Your Parsing Code (You’re Probably Printing the Wrong Thing)
The most likely reason you’re seeing Foundation.JSONDecoder is that your code is printing the decoder instance itself instead of the parsed data. Let’s write a proper parsing flow using URLSession:
func fetchArtworks() { guard let url = URL(string: "http://dronespot.fr/getSpot.php") else { print("Invalid URL—double-check your endpoint!") 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 from the server guard let data = data else { print("No data received") return } // Optional: Print the raw JSON string to verify what you're getting if let rawJSON = String(data: data, encoding: .utf8) { print("Raw JSON response:\n\(rawJSON)") } do { // Important: The JSON is an array, so decode to [Artwork].self, not Artwork.self let artworks = try JSONDecoder().decode([Artwork].self, from: data) // THIS is what you should print—your parsed artworks! print("Successfully fetched \(artworks.count) artworks:") for artwork in artworks { print("- ID: \(artwork.id), Name: \(artwork.name)") } // If you need to update UI, switch to the main thread DispatchQueue.main.async { // Update your table view, collection view, etc. here } } catch { // Critical: Print the decoding error to see exactly what went wrong print("Decoding error: \(error)") // For more detail, cast to DecodingError: if let decodingError = error as? DecodingError { print("Detailed decoding error: \(decodingError)") } } }.resume() // Don't forget to call resume()—otherwise the task won't run! }
Common Mistakes to Fix:
- Printing the decoder instead of parsed data: If you had
print(JSONDecoder())somewhere, that’s why you seeFoundation.JSONDecoder. Replace that with printing yourartworksvariable. - Decoding the wrong type: Since your JSON is an array of artworks, you must use
[Artwork].selfindecode(_:from:). UsingArtwork.selfwill throw an error. - Forgetting
resume(): TheURLSessiontask won’t execute unless you callresume()at the end. - Ignoring errors: Always print decoding errors—they’ll tell you exactly what’s wrong (e.g., "key not found" or "type mismatch").
Final Steps to Debug
- Call
fetchArtworks()from your view controller’sviewDidLoad()or another appropriate place. - Check the console for:
- The raw JSON string to confirm the server is sending valid JSON.
- Any network or decoding errors.
- The list of parsed artworks if everything works.
If you still run into issues, share the exact error message from the console and your full Artwork struct—we can dig deeper!
内容的提问来源于stack exchange,提问作者R1'

