Skip to content

JSON null support for optional swift types? #124

@ecito

Description

@ecito

Optional properties don't accept null values

Issue

The @Schemable macro generates schemas for optional properties (Int?, String?, etc.) that accept missing fields but reject explicit null values.

@Schemable
struct User {
  let name: String
  let age: Int?
}

Works:

{"name": "Alice"}

Fails:

{"name": "Alice", "age": null}

Error: Type mismatch: the instance of type 'null' does not match the expected type 'integer'

Current Behavior

For let age: Int?, the macro generates:

JSONProperty(key: "age") {
  JSONInteger()  // Only accepts integers, rejects null
}
// Not required, so can be omitted

Expected Behavior

Optional properties should accept both the unwrapped type and null values, since many APIs explicitly send null for absent values.

Possible Solutions

  1. .orNull() modifier - Add a new modifier and apply to optionals
  2. OneOf composition - Wrap optional types in OneOf([type, null])
  3. Type array - Use {"type": ["integer", "null"]} if supported

Which approach would you prefer? Happy to submit a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions