Skip to content

C#: add an opt-in Newtonsoft-compatible nullable reference output mode #3097

Description

@foobra

Problem

When generating C# models for an API whose object properties are optional, the Newtonsoft renderer can emit properties such as:

[JsonProperty("profile", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
public Profile Profile { get; set; }

This is awkward for consumers using nullable reference types: the property can be absent from JSON, so its default value after deserialization is null, but the generated C# declaration is non-nullable. With --check-required, an explicit JSON null can also be rejected by Newtonsoft.Json.

The generated FromJson helper also returns a non-nullable model and directly propagates deserialization exceptions.

Reproduction

Schema:

{
  "title": "Request",
  "type": "object",
  "properties": {
    "profile": {
      "type": "object",
      "properties": {
        "id": { "type": "string" }
      }
    },
    "displayName": { "type": "string" }
  }
}

Command:

quicktype \
  --src request.schema.json \
  --src-lang schema \
  --lang csharp \
  --framework NewtonSoft \
  --csharp-version 6 \
  --features complete \
  --check-required \
  --out Request.cs

Requested behavior

Please add an opt-in renderer option, without changing existing defaults, for consumers that want this compatibility behavior:

  • enable nullable reference annotations for optional reference properties;
  • avoid emitting Required.DisallowNull for properties that may be absent;
  • make the top-level FromJson helper's nullable result explicit;
  • preserve the current output when the option is not supplied.

A possible name is --csharp-nullable-reference-types or another name that fits the existing option model.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions