Uploaded image for project: 'Swift'
  1. Swift
  2. SR-9232

Optionals with nil value do not get encoded to JSON

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:

      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) -> "{}"
      

       

       

       

       

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              Peter de Kraker Peter de Kraker
            • Votes:
              7 Vote for this issue
              Watchers:
              11 Start watching this issue

              Dates

              • Created:
                Updated: