I want to encode an optional field with Swift's JSONEncoderusing a struct that conforms to the Encodable protocol.
The default setting is that JSONEncoder uses the encodeIfPresent method, which means that values that are nil are excluded from the Json.
How can I override this for a single property without writing my custom encode(to encoder: Encoder) function, in which I have to implement the encoding for all properties (like this article suggests under "Custom Encoding" )?
Example:
struct MyStruct: Encodable {
let id: Int
let date: Date?
}
let myStruct = MyStruct(id: 10, date: nil)
let jsonData = try JSONEncoder().encode(myStruct)
print(String(data: jsonData, encoding: .utf8)!) // {"id":10}