How to set json serializer settings in asp.net core 3?

后端 未结 3 1012
执笔经年
执笔经年 2020-12-05 22:42

json serializer settings for legacy asp.net core applications were set by adding AddMvc().AddJsonOptions(), but I don\'t use AddMvc() in asp.

相关标签:
3条回答
  • 2020-12-05 22:54

    Option A. AddControllers

    This is still MVC, and requires Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package, but you said you use AddControllers.

    From Add Newtonsoft.Json-based JSON format support

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        // Use the default property (Pascal) casing
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    
        // Configure a custom converter
        options.SerializerOptions.Converters.Add(new MyCustomJsonConverter());
    });
    

    Option B. DefaultSettings

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings (...)

    JsonConvert.DefaultSettings Property

    Gets or sets a function that creates default JsonSerializerSettings. Default settings are automatically used by serialization methods on JsonConvert, and ToObject () and FromObject(Object) on JToken. To serialize without using any default settings create a JsonSerializer with Create().

    0 讨论(0)
  • 2020-12-05 23:01

    Adding Newtonsoft is not necessary, quite a problems with adding Newtonsoft compatibility packages on .Net Core 3.0 project.

    See also https://github.com/aspnet/AspNetCore/issues/13564

    Of course, one would celebrate property naming PascalCase, NA at the moment... So null for PropertyNamingPolicy means PascalCase, which is obviously not very good.

    // Pascal casing
    services.AddControllersWithViews().
            AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
    
    0 讨论(0)
  • 2020-12-05 23:12

    AddMvc returns an IMvcBuilder implementation, which has a corresponding AddJsonOptions extension method. The new-style methods AddControllers, AddControllersWithViews, and AddRazorPages also return an IMvcBuilder implementation. Chain with these in the same way you would chain with AddMvc:

    services.AddControllers()
        .AddJsonOptions(options =>
        {
            // ...
        });
    

    Note that options here is no longer for Json.NET, but for the newer System.Text.Json APIs. If you still want to use Json.NET, see tymtam's answer

    0 讨论(0)
提交回复
热议问题