How do I handle unknown fields safely using JSON with Swift?

When working with JSON in Swift, you might encounter unknown fields that can lead to crashes or unexpected behavior if not handled properly. Here’s a safe way to handle those unknown fields in your JSON data.

let jsonData = """ { "name": "John Doe", "age": 30, "extraField": "this field is not defined in our model" } """.data(using: .utf8)! struct Person: Codable { let name: String let age: Int // Use a dictionary to capture unknown fields let additionalInfo: [String: AnyCodable] enum CodingKeys: String, CodingKey { case name case age case additionalInfo = "extraField" } } // Custom type to handle any kind of JSON struct AnyCodable: Codable { let value: Any init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let intValue = try? container.decode(Int.self) { value = intValue } else if let stringValue = try? container.decode(String.self) { value = stringValue } else { value = "" } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if let intValue = value as? Int { try container.encode(intValue) } else if let stringValue = value as? String { try container.encode(stringValue) } } } do { let person = try JSONDecoder().decode(Person.self, from: jsonData) print(person) } catch { print("Failed to decode JSON:", error) }

Swift JSON Codable unknown fields error handling