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

Swift中Alamofire反序列化MYOBJECT不遵循Decodable的问题咨询

Great questions—let’s work through each one step by step to get your Alamofire decoding working properly:

1. Do you need to duplicate the object?

Nope, you don’t have to duplicate anything from the backend. The CountryObject you showed is Kotlin code running on your server—your Swift project should have its own corresponding model struct/class (which you’re calling MYOBJECT) that mirrors this structure. You only need to modify this Swift model to conform to Decodable—no changes to the backend code are required here.

2. How to make your Swift MYOBJECT conform to Decodable?

Making a Swift struct conform to Decodable is super simple, especially since your property names match the JSON keys exactly (both country and name are the same in the Kotlin data class and the JSON response).

If your Swift model doesn’t inherit from any other protocols/classes yet, just add Decodable to the definition:

struct CountryObject: Decodable {
    let country: String
    let name: String
}

If you have a base ResponseObject protocol in Swift (matching the Kotlin one), just add Decodable alongside it:

struct CountryObject: ResponseObject, Decodable {
    let country: String
    let name: String
}

The Swift compiler will automatically generate all the decoding logic you need because the property names align perfectly with the JSON keys. If you ever have mismatched keys later, you can add a CodingKeys enum to map them, but that’s unnecessary here.

3. Is your Alamofire deserialization approach correct?

Your core approach is on the right track, but there are a couple of safety improvements you should make to avoid crashes and handle errors properly:

  • Always unwrap the data safely: Right now, if the request fails and responseData.data is nil, passing it to JSONDecoder will crash your app.
  • Handle both network errors and decoding errors separately: Alamofire’s response gives you a result enum that lets you distinguish between a failed network request and a successful request with invalid JSON.

Here’s a revised version of your code with these fixes:

Alamofire.request("myurl", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
    .responseData { response in
        switch response.result {
        case .success(let data):
            do {
                // Replace MYOBJECT with your actual Swift struct name (e.g., CountryObject)
                let country = try JSONDecoder().decode(CountryObject.self, from: data)
                // Use your decoded object here—update UI, save to storage, etc.
                print("Successfully decoded country: \(country.name)")
            } catch let decodingError {
                print("Decoding failed: \(decodingError)")
                // Handle decoding issues (e.g., show an error message to the user)
            }
        case .failure(let networkError):
            print("Network request failed: \(networkError)")
            // Handle network problems (e.g., no internet connection, server down)
        }
    }

One small side note: For GET requests, Alamofire defaults to URLEncoding.default, but since you’re not passing any parameters, using JSONEncoding.default won’t cause issues here. Just keep that in mind for future requests where you do need to send parameters with GET.

内容的提问来源于stack exchange,提问作者jamesCode

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:37:50