Blame view

netcore/src/Infrastructure/NCC/JsonSerialization/Converters/DateTimeJsonConverter.cs 1.6 KB
de2bd2f9   “wangming”   项目初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  using NCC.Dependency;
  using System;
  using System.Text.Json;
  using System.Text.Json.Serialization;
  
  namespace NCC.JsonSerialization
  {
      /// <summary>
      /// DateTime 类型序列化
      /// </summary>
      [SuppressSniffer]
      public class DateTimeJsonConverter : JsonConverter<DateTime>
      {
          /// <summary>
          /// 默认构造函数
          /// </summary>
          public DateTimeJsonConverter()
          {
              Format ??= "yyyy-MM-dd HH:mm:ss";
          }
  
          /// <summary>
          /// 构造函数
          /// </summary>
          /// <param name="format"></param>
          public DateTimeJsonConverter(string format)
          {
              Format = format;
          }
  
          /// <summary>
          /// 时间格式化格式
          /// </summary>
          public string Format { get; private set; }
  
          /// <summary>
          /// 反序列化
          /// </summary>
          /// <param name="reader"></param>
          /// <param name="typeToConvert"></param>
          /// <param name="options"></param>
          /// <returns></returns>
          public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
          {
              return DateTime.Parse(reader.GetString());
          }
  
          /// <summary>
          /// 序列化
          /// </summary>
          /// <param name="writer"></param>
          /// <param name="value"></param>
          /// <param name="options"></param>
          public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
          {
              writer.WriteStringValue(value.ToString(Format));
          }
      }
  }