.net core webapi教程-设置日期型字段返回Json格式
深山老妖浏览:11002023-11-30 08:24:54本文累计收益:0我也要赚钱

asp.net core webapi默认返回的json日期列类型格式比较复杂,本文讲解如何将webapi返回的json格式日期列进行格式化。

新建一个.net core webapi项目,并新建一个用于返回的TestModel类。

1
2
3
4
5
6
7
8
9
10
namespace NetCoreStudy.Model
{
    public class TestModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime CreatedDate { get; set; }
    }
}

然后新增一个ValuesController。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using Microsoft.AspNetCore.Mvc;
using NetCoreStudy.Model;
 
namespace NetCoreStudy.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public string Test()
        {
            return "ok";
        }
        [HttpGet]
        public List<TestModel> GetTest()
        {
            var list = new List<TestModel>();
            list.Add(new TestModel() { Id = 123, Name = "张三", Description = "测试描述", CreatedDate = DateTime.Now });
            list.Add(new TestModel() { Id = 234, Name = "李四", Description = "测试描述", CreatedDate = DateTime.Now });
            return list;
        }
    }
}

项目代码截图如下:

运行项目返回Json格式如下:

从上图可以看到返回json数据首字母都是小写的,下面讲如何配置成大写的,首先导入Microsoft.AspNetCore.Mvc.NewtonsoftJson包。然后在Program.cs进行配置。代码如下:

builder.Services.AddControllers().AddNewtonsoftJson(options => {
    //配置返回Json大小写格式与Model一致
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    //统一设置日期格式
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

运行测试返回json格式如下:

至此配置已完成。

评论列表
发表评论
+ 关注