首页 > 其他分享 >JsonSerializerOptions 时间带T处理

JsonSerializerOptions 时间带T处理

时间:2022-11-21 22:33:30浏览次数:63  
标签:return string 处理 DateTime public 时间 dt JsonSerializerOptions

         /// <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;
            }
        }

 

标签:return,string,处理,DateTime,public,时间,dt,JsonSerializerOptions
From: https://www.cnblogs.com/wxbug/p/16913606.html

相关文章