glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
12.31k stars 1.07k forks source link

[FEATURE]: CSharp - make emitting DateOnlyConverter & TimeOnlyConverter optional #2629

Open Thomas-Avery opened 3 months ago

Thomas-Avery commented 3 months ago

Add a rendererOptions section for C# to exclude the generated DateOnlyConverter and TimeOnlyConverter when using the System.Text.Json serialization framework.

For C# projects targeting the .NET Standard DateOnly and TimeOnly can't be used since these types are only available in .NET 6+.

Context (Input, Language)

Input Format: JSON Schema

Output Language: C#

Description

When generating C# code from a JSON schema, I would like to be able to use the C# code in a .NET library targeting the .NET Standard while using theSystem.Text.Json serialization framework.

.NET Standard provides wide support for consumers of a library (.NET Framework 4.6.1+ and .NET & .NET Core 2.0+)

Current Behavior / Output

Go to https://app.quicktype.io/

Choose the JSON schema pokedex-schema.json example.

Select the following language options:

Create a .NET library project

dotnet new classlib --framework netstandard2.0
dotnet add package System.Text.Json

Copy over the C# code from QuickType.

Build the library

dotnet build

Note build errors.

Error CS0246 : The type or namespace name 'DateOnly' could not be found (are you missing a using directive or an assembly reference?)
Error CS0246 : The type or namespace name 'TimeOnly' could not be found (are you missing a using directive or an assembly reference?)

Proposed Behavior / Output

Go to https://app.quicktype.io/

Choose the JSON schema pokedex-schema.json example.

Select the following language options:

Create a .NET library project

dotnet new classlib --framework netstandard2.0
dotnet add package System.Text.Json

Copy over the C# code from QuickType.

Build the library

dotnet build

The .NET library builds successfully.

Solution

Add a language configuration option to indicate if the output should support .NET Standard.

When that configuration option is selected, the DateOnlyConverter and TimeOnlyConverter are not emitted.

Alternatives

It looks like in version 7.0+ of the System.Text.Json package these converters are included. https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-7/

A potential solution is to remove the custom DateOnlyConverter & TimeOnlyConverter from the output and rely on the built-in converters from System.Text.Json.

I don't have enough context to know if this is a realistic solution.

Currently using the Newton Soft serialization framework does look to work with .NET Standard libraries. I think having both serialization frameworks work for .NET Standard libraries would be good.

Context

If we can settle on a solution, I would be happy to help if desired.