解决.Net6 中System.Text.Json序列化和反序列化的时间格式问题

using System.Text.Json;
using System.Text.Json.Serialization;

public static class JsonHelper
    {             
        public static string SerializeObject<T>(T obj)
        {
            if (obj == null)
                return string.Empty;

            var jsonOption = new JsonSerializerOptions();
            jsonOption.Converters.Add(new DatetimeJsonConverter());

            string str = JsonSerializer.Serialize<T>(obj, jsonOption);

            return str;

        }

        public static T DeserializeObject<T>(string jsonText)
        {
            var jsonOption = new JsonSerializerOptions();
            jsonOption.Converters.Add(new DatetimeJsonConverter());

            return JsonSerializer.Deserialize<T>(jsonText, jsonOption);
        }

        public class DatetimeJsonConverter : JsonConverter<DateTime>
        {
            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.String)
                {
                    if (DateTime.TryParse(reader.GetString(), out DateTime date))
                        return date;
                }
                return reader.GetDateTime();
            }

            public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
            {
                writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));

            }
        }
    }

你可能感兴趣的:(.net,json,java)