首页 > 解决方案 > 在flur PostJsonAsync中将枚举序列化为字符串

问题描述

在控制台应用程序中,我使用 Flurl 包向 api 发送请求(api 现在无法正常工作)。我正在尝试验证序列化是否按预期发生。我希望枚举类型被序列化为字符串。程序:

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);
        }
    }

楷模:

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

    }

    public enum SearchCategory
    {
        TimeStamp,
        ModifiedDate,
    }

请求正文的序列化结果是{"SearchCategory":0}我期望的结果{"SearchCategory":"TimeStamp"}。我遵循了 JavaScriptSerializer - JSON serialization of enum as string中提供的解决方案

但似乎不起作用。是否需要进行任何配置或设置才能达到预期。

标签: c#flurl

解决方案


我自己找到了解决方案。在 flurl 配置中添加了一个转换器,如下所示。

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

推荐阅读