jsontypedef / json-typedef-codegen

A CLI tool that generates code from JSON Typedef schemas
https://jsontypedef.com/docs/tools/jtd-codegen
MIT License
160 stars 31 forks source link

Supports optional properties in C# < 8.0? #47

Open twastvedt opened 2 years ago

twastvedt commented 2 years ago

I have a project where I'm generating types for C# and Typescript. In C# I'm stuck on .NET Framework, thus on C# < 8.0. I'd like to be able to use optional properties (for Typescript), but they are turned into nullable reference types in C#, which are only supported in 8.0.

Here's an example. I have this json, which includes an optional reference property.

{
  "definitions": {
    "jobState": {
      "properties": {
        "jobId": {
          "type": "string"
        },
      }
    },
  },
  "properties": {
    "isReady": {
      "type": "boolean"
    }
  },
  "optionalProperties": {
    "jobState": {
      "metadata": { "description": "Current job." },
      "ref": "jobState"
    }
  }
}

It generates this Typescript, which is great (note the question mark after jobState):

export interface Status {
    isReady: boolean;

    /**
     * Current job.
     */
    jobState?: JobState;
}

export interface JobState {
    jobId: string;
}

and this C#, which is only compilable in 8.0. In 7.3 I get this error:

CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.

using System.Text.Json.Serialization;

namespace MyProject
{
    public class Status
    {
        [JsonPropertyName("isReady")]
        public bool IsReady { get; set; }

        /// <summary>
        /// Current job.
        /// </summary>
        [JsonPropertyName("jobState")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public JobState? JobState { get; set; }
    }
}

Can there be a toggle to support C# < 8.0? Thanks!