Newtonsoft.Json 指定某个属性使用特定的时间格式

时间:2021-10-19 04:02:29

Newtonsoft.Json 指定某个属性使用特定的时间格式

Intro

Newtonsoft.Json 是 .NET 下最受欢迎 JSON 操作库,原为 JSON.Net 后改名为 Newtonsoft.Json,之前一直推荐大家使用,除了性能好之外,主要是功能丰富,基本满足所有的可能用到的场景(不区分小写,现在还不行,,)。

遇到这样一个需求,全局使用一种时间格式,某些属性使用特殊的时间格式,这里以一个日期为例

Solution

解决办法:自定义一个 Converter,针对某一个属性使用,DateTimeFormatConverter源码:

using Newtonsoft.Json.Converters;

namespace WeihanLi.Common.Json
{
public class DateTimeFormatConverter : IsoDateTimeConverter
{
public DateTimeFormatConverter(string format)
{
DateTimeFormat = format;
}
}
}

在需要设置格式的属性上设置 Converter https://github.com/WeihanLi/ActivityReservation/blob/dev/ActivityReservation.Helper/ViewModels/ReservationViewModel.cs#L8

[Display(Name = "预约日期")]
[JsonConverter(typeof(DateTimeFormatConverter), "yyyy-MM-dd")]
public DateTime ReservationForDate { get; set; }

请求 api 地址 https://reservation.weihanli.xyz/api/Reservation?pageNumber=1&pageSize=5,返回的数据如下所示:

{
"Data": [
{
"ReservationForDate": "2019-06-10",
"ReservationForTime": "08:00~09:50",
"ReservationPersonPhone": "123****0112",
"ReservationPersonName": "儿**",
"ReservationUnit": "51",
"ReservationPlaceName": "多媒体工作室",
"ReservationActivityContent": "62",
"ReservationId": "f7ab9128-0977-4fd8-9b1a-92648228b397",
"ReservationTime": "2019-06-09 05:19:11",
"ReservationStatus": 1
},
{
"ReservationForDate": "2019-06-12",
"ReservationForTime": "10:00-12:00",
"ReservationPersonPhone": "133****3541",
"ReservationPersonName": "试**",
"ReservationUnit": "ss",
"ReservationPlaceName": "多媒体工作室",
"ReservationActivityContent": "ss",
"ReservationId": "6c145aea-dc14-4ed9-a47f-48c0b79f7601",
"ReservationTime": "2019-06-11 12:45:14",
"ReservationStatus": 0
},
{
"ReservationForDate": "2019-06-17",
"ReservationForTime": "14:00-16:00",
"ReservationPersonPhone": "138****3883",
"ReservationPersonName": "大**",
"ReservationUnit": "1",
"ReservationPlaceName": "多媒体工作室",
"ReservationActivityContent": "1",
"ReservationId": "cebea7bf-44b1-4565-8cdd-78b6156c5f4d",
"ReservationTime": "2019-06-10 02:52:18",
"ReservationStatus": 1
},
{
"ReservationForDate": "2019-06-17",
"ReservationForTime": "08:00-10:00",
"ReservationPersonPhone": "132****4545",
"ReservationPersonName": "冷**",
"ReservationUnit": "技术部",
"ReservationPlaceName": "多媒体工作室",
"ReservationActivityContent": "技术部培训",
"ReservationId": "07f6f8fd-f232-478e-9a94-de0f5fa9b4e9",
"ReservationTime": "2019-06-10 01:44:52",
"ReservationStatus": 2
},
{
"ReservationForDate": "2019-06-22",
"ReservationForTime": "10:00~11:50",
"ReservationPersonPhone": "132****3333",
"ReservationPersonName": "测**",
"ReservationUnit": "测试",
"ReservationPlaceName": "多媒体工作室",
"ReservationActivityContent": "测试",
"ReservationId": "27d0fb7a-ce14-4958-8636-dd10e5526083",
"ReservationTime": "2019-06-18 10:57:06",
"ReservationStatus": 1
}
],
"PageNumber": 1,
"PageSize": 5,
"TotalCount": 18,
"PageCount": 4,
"Count": 5
}

可以看到 ReservationForDate 序列化之后返回的格式如我们指定的格式了~