• System.Text.Json 自定义Converter实现时间转换


    Newtonsoft.Json与System.Text.Json区别

    在 Newtonsoft.Json中可以使用例如
    
    .AddJsonOptions(options =>
                    {
                        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    })
    

    方式设置接收/序列化时间格式,但在.net core 3.1中System.Text.Json是没有自带方式进行转换,这就需要自定义Converter实现时间转换
    官方GitHub地址

    自定义DateTimeJsonConverter

        public class DateTimeJsonConverter : JsonConverter<DateTime>
        {
            private readonly string _dateFormatString;
            public DateTimeJsonConverter()
            {
                _dateFormatString = "yyyy-MM-dd HH:mm:ss";
            }
    
            public DateTimeJsonConverter(string dateFormatString)
            {
                _dateFormatString = dateFormatString;
            }
    
            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                return DateTime.Parse(reader.GetString());
            }
    
            public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
            {
                writer.WriteStringValue(value.ToUniversalTime().ToString(_dateFormatString));
            }
        }
    

    JsonTokenType枚举类型共有以下几种

      /// <summary>Defines the various JSON tokens that make up a JSON text.</summary>
      public enum JsonTokenType : byte
      {
        /// <summary>There is no value (as distinct from <see cref="F:System.Text.Json.JsonTokenType.Null" />).</summary>
        None,
        /// <summary>The token type is the start of a JSON object.</summary>
        StartObject,
        /// <summary>The token type is the end of a JSON object.</summary>
        EndObject,
        /// <summary>The token type is the start of a JSON array.</summary>
        StartArray,
        /// <summary>The token type is the end of a JSON array.</summary>
        EndArray,
        /// <summary>The token type is a JSON property name.</summary>
        PropertyName,
        /// <summary>The token type is a comment string.</summary>
        Comment,
        /// <summary>The token type is a JSON string.</summary>
        String,
        /// <summary>The token type is a JSON number.</summary>
        Number,
        /// <summary>The token type is the JSON literal true.</summary>
        True,
        /// <summary>The token type is the JSON literal false.</summary>
        False,
        /// <summary>The token type is the JSON literal null.</summary>
        Null,
      }
    

    services.AddMvc 中 Newtonsoft.Json与System.Text.Json 配置区别

    .netcore 2.1

                services
                    //全局配置Json序列化处理
                    .AddJsonOptions(options =>
                    {
                        //忽略循环引用
                        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                        //不使用驼峰样式的key
                        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                        //设置时间格式
                        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    })
    

    .netcore 3.1

                services.AddControllers()
                    .AddJsonOptions(options =>
                    {
                        //设置时间格式
                        options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
                        //设置bool获取格式
                        options.JsonSerializerOptions.Converters.Add(new BoolJsonConverter());
                        //不使用驼峰样式的key
                        options.JsonSerializerOptions.PropertyNamingPolicy = null;
                        //不使用驼峰样式的key
                        options.JsonSerializerOptions.DictionaryKeyPolicy = null;
                        //获取或设置要在转义字符串时使用的编码器
                        options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
                    });
    

    bool型转换问题

    .netcore 3.1中接收的json中不能将 "true"/"false"识别为boolean的True/False,这也需要自定义Converter实现bool转换

    namespace Kdniao.Core.Utility
    {
        public class BoolJsonConverter : JsonConverter<bool>
        {
            public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False)
                    return reader.GetBoolean();
    
                return bool.Parse(reader.GetString());
            }
    
            public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
            {
                writer.WriteBooleanValue(value);
            }
        }
    }
    
  • 相关阅读:
    BZOJ 1630/2023 Ant Counting 数蚂蚁
    BZOJ 3997 组合数学
    BZOJ 2200 道路与航线
    BZOJ 3181 BROJ
    BZOJ 4011 落忆枫音
    BZOJ 4027 兔子与樱花
    vijos 1741 观光公交
    vijos 1776 关押罪犯
    vijos 1780 开车旅行
    5、异步通知机制
  • 原文地址:https://www.cnblogs.com/createwell/p/12742132.html
Copyright © 2020-2023  润新知