Serialization of enum to string in flurl PostJsonAsync

1k Views Asked by At

In a console application I am using Flurl package to send a request to an api(the api is not working right now).I am trying to verify whether the serialisation happens as expected.Where I expect the enum type to be serialised to string. Program:

class Program
    {
        private static async Task HandleFlurlErrorAsync(HttpCall call)
        {
            string body = call.RequestBody;
        }
        static async Task Main(string[] args)
        {
            FlurlHttp
            .Configure(settings =>
            {
                settings.OnErrorAsync = HandleFlurlErrorAsync;
            });
            var model = new SearchBy
            { 
                SearchCategory = SearchCategory.TimeStamp
            };
            var person = await "https://api.com".PostJsonAsync(model);
        }
    }

Models:

public class SearchBy
    {
        [JsonConverter(typeof(StringEnumConverter))]
        public SearchCategory SearchCategory { get; set; }

    }

    public enum SearchCategory
    {
        TimeStamp,
        ModifiedDate,
    }

Serialisation result of the request body is{"SearchCategory":0},where as my expectation was {"SearchCategory":"TimeStamp"}. I followed the solution provided in JavaScriptSerializer - JSON serialization of enum as string

but seems to be not working. Is there any configuration or setup needs to be done to achieve the expectation.

1

There are 1 best solutions below

2
On

I found solution myself.Added a converter in flurl configuration as shown below.

 FlurlHttp
            .Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings();
                jsonSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                
                settings.OnErrorAsync = HandleFlurlErrorAsync;
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });