Skip to content

Commit

Permalink
Merge pull request #20 from bonsai-rx/feature-dev
Browse files Browse the repository at this point in the history
Use StringEnumConverter for string enum types
  • Loading branch information
glopesdev authored Jan 8, 2024
2 parents 2b332c7 + 9ba745f commit 66bdded
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
35 changes: 34 additions & 1 deletion Bonsai.Sgen.Tests/EnumGenerationTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NJsonSchema;
Expand Down Expand Up @@ -44,5 +45,37 @@ public void GenerateStringEnum_SerializerAnnotationsUseStringValues()
Assert.IsTrue(code.Contains("EnumMemberAttribute(Value=\"A\")"));
Assert.IsTrue(code.Contains("YamlMemberAttribute(Alias=\"A\")"));
}

[TestMethod]
public async Task GenerateStringEnum_StringEnumTypeDefinitionWithStringEnumConverter()
{
var schema = await JsonSchema.FromJsonAsync(@"
{
""$schema"": ""http://json-schema.org/draft-04/schema#"",
""type"": ""object"",
""title"": ""Container"",
""additionalProperties"": false,
""properties"": {
""Enum"": {
""$ref"": ""#/definitions/StringEnum""
}
},
""definitions"": {
""StringEnum"": {
""enum"": [
""This is a string A"",
""This is a string B""
],
""title"": ""StringEnum"",
""type"": ""string""
}
}
}
");
var generator = TestHelper.CreateGenerator(schema);
var code = generator.GenerateFile();
Assert.IsTrue(code.Contains("StringEnumConverter"));
CompilerTestHelper.CompileFromSource(code);
}
}
}
9 changes: 9 additions & 0 deletions Bonsai.Sgen/CSharpEnumTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using NJsonSchema.CodeGeneration.CSharp.Models;
using YamlDotNet.Serialization;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Bonsai.Sgen
{
Expand Down Expand Up @@ -33,6 +35,13 @@ public override void BuildType(CodeTypeDeclaration type)
type.Comments.Add(new CodeCommentStatement("</summary>", docComment: true));
}

if (Model.IsStringEnum && Settings.SerializerLibraries.HasFlag(SerializerLibraries.NewtonsoftJson))
{
type.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(JsonConverter)),
new CodeAttributeArgument(new CodeTypeOfExpression(typeof(StringEnumConverter)))));
}

if (Model.IsEnumAsBitFlags)
{
type.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName));
Expand Down

0 comments on commit 66bdded

Please sign in to comment.