JsonSerializerOptions 时间带T处理

         /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJSON(object obj)
        {
            try
            {
                if (obj == null || obj.ToString() == null) return "";

                JsonSerializerOptions options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Converters = { new DateTimeJsonConverter() },
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All)
                };

                byte[] b = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj, options));
                return Encoding.UTF8.GetString(b);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }

        public class DateTimeJsonConverter : JsonConverter<DateTime>
        {
            private readonly string Format;
            public DateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss")
            {
                Format = format;
            }
            public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
            {
                writer.WriteStringValue(date.ToString(Format));
            }
            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                // 获取时间类型的字符串
                var dt = reader.GetString();
                if (!string.IsNullOrEmpty(dt))
                {
                    //将日期与时间之间的"T"替换为一个空格,将结尾的"Z"去掉,否则会报错
                    dt = dt.Replace("T", " ").Replace("Z", "");
                    //取到秒,毫秒内容也要去掉,经过测试,不去掉会报错
                    if (dt.Length > 19)
                    {
                        dt = dt.Substring(0, 19);
                    }
                    return DateTime.ParseExact(dt, Format, null);
                }
                return DateTime.Now;
            }
        }

 

posted @ 2022-11-21 22:24  懒人境界  阅读(379)  评论(0编辑  收藏  举报