添加程序集:System.Text.Json
using System.Text.Json; using System.Text.Json.Serialization;
响应时间格式,中文乱码,响应驼峰命名
services.AddControllers(x=> { //x.Filters.Add(); }) .AddJsonOptions(options=> { //options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase; options.JsonSerializerOptions.PropertyNamingPolicy = null; //响应驼峰命名 options.JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;//中文乱码 options.JsonSerializerOptions.Converters.Add(new Common.SystemTextJsonConvert.DateTimeConverter());//应时间格式 options.JsonSerializerOptions.Converters.Add(new Common.SystemTextJsonConvert.DateTimeNullableConverter()); //应时间格式 }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
public class SystemTextJsonConvert { 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")); } } }
获取默认JsonSerializerOptions 对象:
public static class JsonOpt { public static JsonSerializerOptions UnicodeRangesAll { get { return DefaultOptions(); } } public static JsonSerializerOptions IgnoreNullValues { get { JsonSerializerOptions options = DefaultOptions(); options.IgnoreNullValues = true; return options; } } public static JsonSerializerOptions DefaultOptions(string dateTimeFormat = "yyyy-MM-dd HH:mm:ss") { JsonSerializerOptions Options = new JsonSerializerOptions() { PropertyNamingPolicy = null, WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All) }; Options.Converters.Add(new DateTimeConverterUsingDateTimeParse(dateTimeFormat)); return Options; } }
注册服务代码其实还是可以优化的,有时间的朋友去搞吧!
付:
控制台 System.Text.Json 中文乱码问题:
var options = new JsonSerializerOptions();
options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);
var json = JsonSerializer.Serialize(new { title = "代码改变世界" }, options);