How can I decode a JSON to a Swift struct ignoring all the fields that are not in both the json and the struct?

I’m getting an exception when decoding this json to the Device struct below. JSON { "SerialNumber": "123", "Model": "iPhone14" "Brand": "Apple" } Swift struct: struct Device : Codable, Identifiable { var id = UUID().uuidString let SerialNumber : String let Model : String let Brand : String } To get around this, I have to add… Read More How can I decode a JSON to a Swift struct ignoring all the fields that are not in both the json and the struct?

Clarifications on JSONDecoder when decoding a single value

I was trying to perform some tests on JSONDecoder and I’ve encountered a strange behavior. In particular, when I use the following code an error is thrown. let data = "Sample String".data(using: .utf8)! do { let decoder = JSONDecoder() let decoded = try decoder.decode(String.self, from: data) print(decoded) } catch { print(error) } dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription:… Read More Clarifications on JSONDecoder when decoding a single value

Swift JSONDecoder: how to decode a JSON with unknown keys at the top-level?

I would like to know how I can decode this JSON: { "unknown_key1": { "info": "Info text", "text": "More text" }, "unknown_key2": { "info": "Info text", "text": "More text" }, … } I have started writing something like this: JSONDecode().decode(Test.self, from: data) Test struct Test: Decodable { let content: [String: Content] } struct Content: Decodable… Read More Swift JSONDecoder: how to decode a JSON with unknown keys at the top-level?