ASP.NET MVC Core API Serialize Enums to String

前端 未结 2 470
北海茫月
北海茫月 2020-12-30 20:54

How to serialize Enum fields to String instead of an Int in ASP.NET MVC Core 3.0? I\'m not able to do it the old way.

services.AddMvc().AddJsonOptions(opts          


        
2条回答
  •  孤城傲影
    2020-12-30 21:01

    New System.Text.Json serialization

    ASP.NET MVC Core 3.0 uses built-in JSON serialization. Use System.Text.Json.Serialization.JsonStringEnumConverter (with "Json" prefix):

    services
        .AddMvc()
        // Or .AddControllers(...)
        .AddJsonOptions(opts =>
        {
            opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        })
    

    More info here. The documentation can be found here.

    If you prefer Newtonsoft.Json

    You can also use "traditional" Newtonsoft.Json serialization:

    Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
    

    And then:

    services
        .AddControllers()
        .AddNewtonsoftJson(opts => opts.Converters.Add(new StringEnumConverter()));
    

提交回复
热议问题