Swift 4:使用JSONDecoder解析Alamofire响应的嵌套结构体问题
First, let's fix the core issue in your code: you're using responseJSON which parses the response into a JSON object (like [String: Any] or [Any]), but JSONDecoder requires raw Data to work. Trying to cast response.result.value to Data will always fail here—that's why you're hitting problems.
Here's the revised, safe implementation:
sessionManager.request(self.url_report + "?d=" + date, method: .get) .responseData { response in switch response.result { case .success(let data): guard response.response?.statusCode == 200 else { debugPrint("Unexpected status code: \(response.response?.statusCode ?? -1)") return } do { let report = try JSONDecoder().decode(Report.self, from: data) // Use your decoded Report object here print("Successfully decoded report: \(report)") } catch { debugPrint("Decoding error: \(error.localizedDescription)") // Optional: Print detailed error info for debugging debugPrint("Full error: \(error)") } case .failure(let error): debugPrint("Request failed: \(error.localizedDescription)") } }
Key Fixes & Improvements:
- Used
responseDatainstead ofresponseJSON: This gives us the rawDatadirectly from the network response, which is exactly whatJSONDecoderneeds. No unnecessary parsing and re-serializing. - Removed force casts: Replaced risky
as! Datawith safe optional handling and switch cases for Alamofire's result. - Proper error handling: Added a full
do-catchblock to catch decoding errors, and handled network request failures separately. - Status code check: Wrapped the status code check inside the success case to avoid accessing
response.responsewhen the request failed.
Additional Tips for Codable Structs:
Make sure your nested structs (Student, VIO, StuPresence) also conform to Codable, and that their property names exactly match the keys in the JSON response (unless you use CodingKeys to map them). For example, if your JSON uses student instead of s, you'll need to add a CodingKeys enum to your Report struct:
public struct Report: Codable { let s: Student let vio: [VIO] let stuPresence: [StuPresence] enum CodingKeys: String, CodingKey { case s = "student" case vio case stuPresence = "student_presence" } }
If you're still having issues, print the full decoding error (as shown in the code) to get details about which key or type is mismatching—it's usually a property name or type mismatch between your structs and the JSON.
内容的提问来源于stack exchange,提问作者AlexP

