Swift中如何将JSON的Float值解析为结构体的Int类型?
This error pops up because your Swift model expects an Int for the counterLeft field, but the backend is sending a floating-point number (like 53422.434) instead. Swift's default JSONDecoder enforces strict type matching, so it throws this corruption error when the types don't align.
Here are a few practical solutions to handle this, depending on your needs:
1. Custom Field-Level Decoding (Best for Specific Fields)
If only a handful of fields have this issue, override the decoding logic for your model to handle both Int and Double inputs. This keeps the rest of your decoding strict and avoids unintended side effects.
struct Game: Codable { var counterLeft: Int enum CodingKeys: String, CodingKey { case counterLeft } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // First try decoding as Int (for cases where backend returns correctly) do { counterLeft = try container.decode(Int.self, forKey: .counterLeft) } catch DecodingError.typeMismatch { // If that fails, decode as Double and convert to Int let doubleValue = try container.decode(Double.self, forKey: .counterLeft) // Choose truncation or rounding based on your requirements: counterLeft = Int(doubleValue) // Truncates decimal part (e.g. 53422.434 → 53422) // OR // counterLeft = Int(doubleValue.rounded()) // Rounds to nearest integer (e.g. 53422.434 → 53422, 53422.6 → 53423) } } }
2. Global Decoder Strategy (Quick Fix for All Int Fields)
If this issue affects multiple Int fields across your models, you can configure the JSONDecoder to automatically convert floating-point numbers to Ints globally. Note that this applies to all Int decodings, so use this only if you're sure all such cases should be handled this way.
let decoder = JSONDecoder() decoder.numberDecodingStrategy = .custom { container in let number = try container.decode(Double.self) // Ensure the number fits within Int's range to avoid overflow guard number >= Double(Int.min) && number <= Double(Int.max) else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Number \(number) is out of Int range" ) } return Int(number) // Or use rounded() here if needed } // Now use this decoder to parse your response: do { let response = try decoder.decode(HomeResponse.self, from: jsonData) } catch { print("Decoding error: \(error)") }
3. Change Model Type to Double/Float (Simplest, But Requires Conversion)
If you don't mind working with a floating-point type in your model temporarily, you can change the field to Double, then convert it to Int when you need to use it. This is the quickest fix but adds a conversion step wherever you access the field.
struct Game: Codable { var counterLeft: Double // Optional: Add a computed property to get the Int value easily var counterLeftInt: Int { Int(counterLeft) // Or rounded() as needed } }
Bonus: Communicate with the Backend
While these fixes will resolve the decoding error, it's worth checking with your backend team to understand why the Int parameter was changed to Float. If this was an unintended mistake, getting them to revert it would be the cleanest long-term solution.
内容的提问来源于stack exchange,提问作者Nicolas Martinez

