From c51bdf1221ad5015f65829e674f7c5b7a8c301be Mon Sep 17 00:00:00 2001 From: Dan Date: Tue, 1 Aug 2023 14:06:08 -0600 Subject: [PATCH] Convert string to enum and string to boolean --- OFBButte.Api/JsonStringBooleanConverter.cs | 23 ++++++++++++++++++++++ OFBButte.Api/Program.cs | 6 ++++++ 2 files changed, 29 insertions(+) create mode 100644 OFBButte.Api/JsonStringBooleanConverter.cs diff --git a/OFBButte.Api/JsonStringBooleanConverter.cs b/OFBButte.Api/JsonStringBooleanConverter.cs new file mode 100644 index 0000000..2cab8a2 --- /dev/null +++ b/OFBButte.Api/JsonStringBooleanConverter.cs @@ -0,0 +1,23 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + + +public class JsonStringBooleanConverter : JsonConverter +{ + public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var val = reader.GetString(); + if (val == "true") + return true; + + if (val == "false") + return false; + + throw new Exception($"Cannot convert {val} to boolean"); + } + + public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) + { + writer.WriteBooleanValue(value); + } +} diff --git a/OFBButte.Api/Program.cs b/OFBButte.Api/Program.cs index fa0ff03..15aac7e 100644 --- a/OFBButte.Api/Program.cs +++ b/OFBButte.Api/Program.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Serialization; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.Extensions.Options; using OFBButte.Application.Configuration; @@ -21,6 +22,11 @@ builder.Services.AddCors(options => }); }); +builder.Services.ConfigureHttpJsonOptions(options => { + options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.SerializerOptions.Converters.Add(new JsonStringBooleanConverter()); +}); + // App Settings var appSettings = builder.Configuration.GetSection("App").Get(); builder.Services.AddSingleton(appSettings);