Skip to content

[SR-9232] Optionals with nil value do not get encoded to JSON #3594

Open
@swift-ci

Description

@swift-ci
Previous ID SR-9232
Radar None
Original Reporter Peter de Kraker (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 22
Component/s Foundation
Labels Bug, Codable
Assignee bendjones (JIRA)
Priority Medium

md5: d40e1037406253fafe704bc8c33c89d9

Issue Description:

The implementation of Codable and JSONEncoder in Swift 4 do automatically discard optional fields that have nil as value.

I can understand that this is an option, but there is no option to be set and that makes it a big problem for working with JSON API's that expect nulls for nil fields.

I don't really understand why this default is chosen, since removing nulls from JSON is easier afterwards, then adding them manually by needing to write the encode() method for each class.

Anyways, it would be great if an option can be provided to automatically encode nil values to null with JSONEncoder.

class Test : Codable
{
    var optional:Int?
}


let test:Test = Test()
test.optional = nil


let data = try! JSONEncoder().encode(test)
let string = String(data: data, encoding: String.Encoding.utf8)!
print(string) -> "{}"

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions