You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4:使用JSONDecoder解析Alamofire响应的嵌套结构体问题

Correct JSON Decoding with Alamofire and Codable

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 responseData instead of responseJSON: This gives us the raw Data directly from the network response, which is exactly what JSONDecoder needs. No unnecessary parsing and re-serializing.
  • Removed force casts: Replaced risky as! Data with safe optional handling and switch cases for Alamofire's result.
  • Proper error handling: Added a full do-catch block 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.response when 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:58:22