Skip to content

Commit d297774

Browse files
authored
Merge pull request #2 from tskx/patch-2
Serialize enums as strings and use camelCase everywhere
2 parents a618b56 + 376d5d3 commit d297774

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

ProjectTemplates/ReferenceProject/Startup.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,13 @@
1313
using Microsoft.Extensions.Hosting;
1414
using Microsoft.Extensions.Logging;
1515
using Newtonsoft.Json;
16+
using Newtonsoft.Json.Converters;
1617
using Newtonsoft.Json.Serialization;
1718
using ReferenceProject.Filters;
1819
using ReferenceProject.Modules;
1920
using System.IO;
21+
using System.Text.Json;
22+
using System.Text.Json.Serialization;
2023

2124
/*
2225
* This project have been originally created from ASP.Net Core RESTful Service Template.
@@ -41,7 +44,8 @@ public Startup(IConfiguration configuration, IHostEnvironment env)
4144

4245
// See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#content-formatting
4346
JsonConvert.DefaultSettings = () =>
44-
new JsonSerializerSettings()
47+
{
48+
var settings = new JsonSerializerSettings()
4549
{
4650
ContractResolver = new CamelCasePropertyNamesContractResolver(),
4751
NullValueHandling = NullValueHandling.Ignore,
@@ -53,6 +57,9 @@ public Startup(IConfiguration configuration, IHostEnvironment env)
5357
Formatting = Formatting.None
5458
#endif
5559
};
60+
settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
61+
return settings;
62+
};
5663
}
5764

5865
public static IConfiguration Configuration { get; private set; }
@@ -74,6 +81,12 @@ public void ConfigureServices(IServiceCollection services)
7481
options.Filters.Add(new ValidateModelFilter()); // Validate model. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#model-validation
7582
options.Filters.Add(new CacheControlFilter()); // Add "Cache-Control" header. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#cache-control
7683
})
84+
.AddJsonOptions(options =>
85+
{
86+
options.JsonSerializerOptions.IgnoreNullValues = true;
87+
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
88+
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
89+
})
7790
.AddApiExplorer()
7891
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
7992

0 commit comments

Comments
 (0)