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

Advertisements 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… 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

Advertisements 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: [],… Read More Clarifications on JSONDecoder when decoding a single value

Nested Json data won't be decoded using Swift language?

Advertisements I’m receiving response data from an API, when I’m trying to decode it by using json decoder, the nested json data won’t be decoded because it returns null. json data as follow: { "token": "string", "details": { "ID": "string", "Name": "string", "Message": null } } Decoding model is: struct response: Codable { let token:… Read More Nested Json data won't be decoded using Swift language?

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

Advertisements 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:… Read More Swift JSONDecoder: how to decode a JSON with unknown keys at the top-level?

Decode JSON response from API

Advertisements I get some JSON objects from my api that look like this: { "from": "1970-01-01", "until": null, "employeeId": "13", "project": { "id": "05c6adce-20cd-4ca3-9eff-8fd430f63a20", "version": 0, "name": "AGFA", "code": "AGFA", "start": "2016-01-01", "end": "2016-12-31", "alternativeCodes": [] } }, And I want to use the different parts of it in my program. I did some research… Read More Decode JSON response from API