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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?