0

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.

Muralikrishna
  • 159
  • 1
  • 11

1 Answers1

1

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);
            });
Muralikrishna
  • 159
  • 1
  • 11
  • You definitely found the right hook to do it without attributes, although I'm a little surprised it didn't work with them. I don't think `[Serializable]` nor the attribute directly on the `enum` definition are necessary, not sure that would throw it off though. – Todd Menier Oct 16 '20 at 15:39
  • You are correct @ToddMenier. While I was trying many other options I added those attributes.`[JsonConverter(typeof(StringEnumConverter))]`over `enum` definition and `[Serializable]` were unnecessary. Surprisingly it didn't work without them as well, since I already tested them earlier.I will edit the code & update. – Muralikrishna Oct 20 '20 at 09:09