在.Net Framework的时候序列化经常使用Newtonsoft.Json插件来使用,而在.Net Core中自带了System.Text.Json,号称性能更好,今天抽空就来捣鼓一下。
使用起来其实也很简单,就是有些地方要注意,比如在我们的对象实体中有中文的话,直接序列化时中文会被转换成编码格式,时间格式序列化时会被转成默认的格式等。
下面就直接上Demo的代码了
using System; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Unicode; namespace ConsoleApp4 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var user = new User{ Id= 1, Name = "张三李四", Gender = Gender.Male, Email="Jesen@qq.com", CreatedTime = DateTime.Now }; JsonSerializerOptions options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); //解决中文序列化被编码的问题 options.Converters.Add(new DateTimeConverter()); //解决时间格式序列化的问题 var serializeString = JsonSerializer.Serialize(user, options); Console.WriteLine(serializeString); User obj = JsonSerializer.Deserialize<User>(serializeString,options); Console.ReadLine(); } } class User { public int Id { get; set; } public string Name { get; set; } [JsonConverter(typeof(JsonStringEnumConverter))] //解决枚举序列化时被转成数值的问题 public Gender Gender { get; set; } public string Email { get; set; } public DateTime CreatedTime { get; set; } } enum Gender { Male, FaleMale } public class DateTimeConverter : JsonConverter<DateTime> { 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.ToString("yyyy-MM-dd HH:mm:ss")); } } public class DateTimeNullableConverter : JsonConverter<DateTime?> { public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString()); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss")); } } }