Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support configuring whether to generate StringEnumConverter #1646

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NJsonSchema.CodeGeneration.CSharp;
using NJsonSchema.Generation;
using NJsonSchema.NewtonsoftJson.Generation;
using System.Collections.Generic;
using System.Threading.Tasks;
using VerifyXunit;
using Xunit;

using static NJsonSchema.CodeGeneration.CSharp.Tests.VerifyHelper;

namespace NJsonSchema.CodeGeneration.Tests.CSharp
{
[UsesVerify]
public class EnumTests
{
[Fact]
Expand Down Expand Up @@ -167,6 +170,20 @@ public async Task When_enum_is_nullable_then_StringEnumConverter_is_set()
code);
}

[Fact]
public async Task When_StringEnumConverter_is_disabled_attribute_is_not_generated()
{
//// Arrange
var schema = NewtonsoftJsonSchemaGenerator.FromType<MyStringEnumListTest>();
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, GenerateStringEnumConverterAttributes = false });

//// Act
var output = generator.GenerateFile();

//// Assert
await Verify(output);
}

public enum SomeEnum
{
Thing1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Verify.XUnit" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Condition="'$(TargetFramework)' == 'net6.0'" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//----------------------
// <auto-generated>
// Generated using the NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0) (http://NJsonSchema.org)
// </auto-generated>
//----------------------


namespace MyNamespace
{
#pragma warning disable // Disable all warnings

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
public enum MyStringEnum
{

[System.Runtime.Serialization.EnumMember(Value = @"Foo")]
Foo = 0,


[System.Runtime.Serialization.EnumMember(Value = @"Bar")]
Bar = 1,


}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
public partial class MyStringEnumListTest
{
[Newtonsoft.Json.JsonProperty("Enums", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.Generic.ICollection<MyStringEnum> Enums { get; set; }

[Newtonsoft.Json.JsonProperty("NullableEnum", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public MyStringEnum? NullableEnum { get; set; }


}
}
19 changes: 19 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp.Tests/VerifyHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using VerifyTests;
using VerifyXunit;

namespace NJsonSchema.CodeGeneration.CSharp.Tests;

public static class VerifyHelper
{
/// <summary>
/// Helper to run verify tests with sane defaults.
/// </summary>
public static SettingsTask Verify(string output)
{
return Verifier
.Verify(output)
.ScrubLinesContaining(StringComparison.OrdinalIgnoreCase, "Generated using the NSwag toolchain")
.UseDirectory("Snapshots");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public CSharpGeneratorSettings()

RequiredPropertiesMustBeDefined = true;
GenerateDataAnnotations = true;
GenerateStringEnumConverterAttributes = true;
TypeAccessModifier = "public";
PropertySetterAccessModifier = string.Empty;
GenerateJsonMethods = false;
Expand Down Expand Up @@ -64,6 +65,9 @@ public CSharpGeneratorSettings()
/// <summary>Gets or sets a value indicating whether to generated data annotation attributes (default: true).</summary>
public bool GenerateDataAnnotations { get; set; }

/// <summary>Gets or sets a value indicating whether to add string to enum converter attribute for the property (default: true).</summary>
public bool GenerateStringEnumConverterAttributes { get; set; }

/// <summary>Gets or sets the any type (default: "object").</summary>
public string AnyType { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings,
/// <summary>Gets a value indicating whether to use the DateFormatConverter.</summary>
public bool UseDateFormatConverter => _settings.DateType.StartsWith("System.DateTime");

/// <summary>Gets a value indicating whether to use the DateFormatConverter.</summary>
public bool UseStringEnumConverter => _settings.GenerateStringEnumConverterAttributes;

/// <summary>Gets or sets the access modifier of generated classes and interfaces.</summary>
public string TypeAccessModifier => _settings.TypeAccessModifier;

Expand Down
4 changes: 2 additions & 2 deletions src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
// TODO(system.text.json): Add string enum item converter
{%- endif -%}
{%- else -%}
[Newtonsoft.Json.JsonProperty("{{ property.Name }}", Required = {{ property.JsonPropertyRequiredCode }}{% if property.IsStringEnumArray %}, ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter){% endif %})]
[Newtonsoft.Json.JsonProperty("{{ property.Name }}", Required = {{ property.JsonPropertyRequiredCode }}{% if property.IsStringEnumArray and UseStringEnumConverter %}, ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter){% endif %})]
{%- endif -%}
{%- if property.RenderRequiredAttribute -%}
[System.ComponentModel.DataAnnotations.Required{% if property.AllowEmptyStrings %}(AllowEmptyStrings = true){% endif %}]
Expand All @@ -80,7 +80,7 @@
{%- if property.RenderRegularExpressionAttribute -%}
[System.ComponentModel.DataAnnotations.RegularExpression(@"{{ property.RegularExpressionValue }}")]
{%- endif -%}
{%- if property.IsStringEnum -%}
{%- if property.IsStringEnum and UseStringEnumConverter -%}
{%- if UseSystemTextJson -%}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
{%- else -%}
Expand Down
Loading