Include nulls with JSONEncoder

How can I tell JSONEncoder that it SHOULD include they property key even when the optional value is nil? In the generated JSON I want a null. For example:



struct Foo : Codable {
    var id = 7
    var foo: String?
}

let data = try! JSONEncoder().encode(Foo())
String(data: data, encoding: .utf8)


That just prints out


{"id":7}


when what I really want is:


{"id":7,"foo":null}

Replies

Create your own encoder.


See h ttps://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder