WebApi 中使用AddNewtonsoftJson输出Json格式数据

前言:web

        就目前而言,.Net Core WebApi中输出格式几乎都是json,可是在core中使用任何服务都须要配置,这里须要配置 AddNewtonsoftJsonjson

1、咱们来看一个例子:api

        [Route("details")] [HttpGet] public ActionResult<JObject> Details() { var data = new { Id=1, Name="Lucy", Address="珠穆朗玛峰", Time = DateTime.Now }; return JObject.FromObject(data); }

不作任何配置,输出:spa

 

 

 能够看出,并无输出咱们想要的数据。code

处理方法:orm

咱们须要在Startup类中添加AddNewtonsoftJson配置blog

 public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); }

结果输出:文档

 

 

 获得正确的数据。get

2、关于AddNewtonsoftJsonio

ASP.NET Core 3.0 以前的版本中,默认设置使用经过 Newtonsoft.Json 包实现的 JSON 格式化程序。 在 ASP.NET Core 3.0 或更高版本中,默认 JSON 格式化程序基于 System.Text.Json

 Newtonsoft.Json经过安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包并在中进行配置,可得到对基于的格式化程序和功能的支持 Startup.ConfigureServices 。

AddNewtonsoftJson方法具备重载功能,能够进行多项配置,如下是一些经常使用的配置

services.AddControllers() .AddNewtonsoftJson(options => { //修改属性名称的序列化方式,首字母小写,即驼峰样式
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //修改时间的序列化方式1
                options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss" });
                //修改时间的序列化方式2
options.SerializerSettings.DateFormatString = "yyyy/MM/dd HH:mm:ss";
});

从例子中能够看出,配置后的时间格式已经被格式化了。

微软官方文档地址:https://docs.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0

相关文章
相关标签/搜索