Swift 4中如何保证JSON解析有效?合法JSON解析失败求助
Hey there, let's break down why your valid JSON is failing to parse in Swift—this is a super common gotcha with Codable!
The Root Problem
Your JSON is wrapped in square brackets [], which means it's an array of objects, not a single object. Chances are your parsing code is trying to decode it as a single model instance instead of an array of that model.
Step 1: Define Your Codable Model
First, create a struct that matches your JSON structure (make sure the property names match exactly—Codable is case-sensitive by default):
struct RiskScore: Codable { let ID: String let TotalRisk: Double let TotalScore: Double }
Step 2: Fix the Parsing Logic
In your data task completion handler, you need to decode the data into an array of RiskScore instead of a single instance. Here's the corrected code snippet:
// make the request let task = session.dataTask(with: urlRequest) { (data, response, error) in // check for any errors guard error == nil else { print(error!) return } // make sure we got data guard let responseData = data else { print("No data returned from the server") return } do { // Decode as an array of RiskScore (note the [] around RiskScore) let riskScores = try JSONDecoder().decode([RiskScore].self, from: responseData) // Since your JSON only has one object, grab the first element if let firstScore = riskScores.first { print("ID: \(firstScore.ID)") print("Total Risk: \(firstScore.TotalRisk)") print("Total Score: \(firstScore.TotalScore)") } } catch let decodingError { // Print the full error to debug if something still goes wrong print("Decoding failed with error: \(decodingError.localizedDescription)") print("Full error details: \(decodingError)") } } task.resume()
Why This Works
Your original code was probably using RiskScore.self instead of [RiskScore].self in the decode call. Since the JSON root is an array, the decoder expects an array type—mismatching this is the most likely cause of your "invalid" parsing error.
Quick Checks to Avoid Future Issues
- Double-check that your model property names exactly match the JSON keys (case included). If you want to use Swift-style camelCase properties, you can add a
CodingKeysenum to map them. - Always print the full decoding error (not just the localized description) when troubleshooting—it will tell you exactly where the mismatch is.
内容的提问来源于stack exchange,提问作者Joshua Noble

