How to parse JSON with Decodable protocol when property types might change from Int to String? [duplicate]

Well it’s a common IntOrString problem. You could just make your property type an enum that can handle either String or Int. enum IntOrString: Codable { case int(Int) case string(String) init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() do { self = try .int(container.decode(Int.self)) } catch DecodingError.typeMismatch { do { self = try … Read more

What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?

There’s a subtle, but important difference between these two lines of code: // Exhibit 1 foo = try container.decode(Int?.self, forKey: .foo) // Exhibit 2 foo = try container.decodeIfPresent(Int.self, forKey: .foo) Exhibit 1 will parse: { “foo”: null, “bar”: “something” } but not: { “bar”: “something” } while exhibit 2 will happily parse both. So in … Read more

Swift Codable multiple types

You can try struct Root: Codable { let description,id: String let group,groupDescription: String? let name: String let value: MyValue enum CodingKeys: String, CodingKey { case description = “Description” case group = “Group” case groupDescription = “GroupDescription” case id = “Id” case name = “Name” case value = “Value” } } enum MyValue: Codable { case … Read more

How to use Any in Codable Type

Quantum Value First of all you can define a type that can be decoded both from a String and Int value. Here it is. enum QuantumValue: Decodable { case int(Int), string(String) init(from decoder: Decoder) throws { if let int = try? decoder.singleValueContainer().decode(Int.self) { self = .int(int) return } if let string = try? decoder.singleValueContainer().decode(String.self) { … Read more