添加以扩展:
public class TextJsonConverExtension { public static void AddConverters(Microsoft.AspNetCore.Mvc.JsonOptions configure) { //添加支持string转int的操作 configure.JsonSerializerOptions.Converters.Add(new IntToStringConverter()); configure.JsonSerializerOptions.Converters.Add(new StringToStringConverter()); configure.JsonSerializerOptions.Converters.Add(new LongToStringConverter()); } } public class IntToStringConverter : JsonConverter<Int32> { public override Int32 Read(ref System.Text.Json.Utf8JsonReader reader, Type type, System.Text.Json.JsonSerializerOptions options) { if (reader.TokenType == System.Text.Json.JsonTokenType.String) { ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (System.Buffers.Text.Utf8Parser.TryParse(span, out Int32 number, out int bytesConsumed) && span.Length == bytesConsumed) return number; if (Int32.TryParse(reader.GetString(), out number)) return number; } return reader.GetInt32(); } public override void Write(Utf8JsonWriter writer, Int32 value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } } public class StringToStringConverter : JsonConverter<String> { public override String Read(ref System.Text.Json.Utf8JsonReader reader, Type type, System.Text.Json.JsonSerializerOptions options) { if (reader.TokenType == System.Text.Json.JsonTokenType.String) { return reader.GetString(); } else if(reader.TokenType == System.Text.Json.JsonTokenType.Number) { ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (System.Buffers.Text.Utf8Parser.TryParse(span, out Int32 number, out int bytesConsumed) && span.Length == bytesConsumed) return number.ToString(); if (Int32.TryParse(reader.GetString(), out number)) return number.ToString(); } return null; //return reader.GetInt32(); } public override void Write(Utf8JsonWriter writer, String value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } } public class LongToStringConverter : JsonConverter<long> { public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (Utf8Parser.TryParse(span, out long number, out int bytesConsumed) && span.Length == bytesConsumed) return number; if (Int64.TryParse(reader.GetString(), out number)) return number; } return reader.GetInt64(); } public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } }
使用:
services.AddMvc(options => { }).AddJsonOptions(options => { //添加json的扩展 TextJsonConverExtension.AddConverters(options); //解决中文自动编码 options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); });
更多参考:https://github.com/dotnet/runtime/issues/30255
评论区