- 症状
- 入参
- 未进行优化(3.1默认序列化规则)序列化之后的参数
- 解决方案
- 新增序列化规则
public class ObjectToInferredTypesConverter : JsonConverter<object> { public override object Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.True) { return true; } if (reader.TokenType == JsonTokenType.False) { return false; } if (reader.TokenType == JsonTokenType.Number) { if (reader.TryGetInt64(out long l)) { return l; } return reader.GetDouble(); } if (reader.TokenType == JsonTokenType.String) { if (reader.TryGetDateTime(out DateTime datetime)) { return datetime; } return reader.GetString(); } // Use JsonElement as fallback. // Newtonsoft uses JArray or JObject. using JsonDocument document = JsonDocument.ParseValue(ref reader); return document.RootElement.Clone(); } public override void Write( Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options) => throw new InvalidOperationException("Should not get here."); }
- service 添加规则
services.AddControllers().AddJsonOptions(config => { config.JsonSerializerOptions.Converters.Add(new ObjectToInferredTypesConverter()); //设置时间格式 //config.JsonSerializerOptions.DateFormatString = "yyyy-MM-dd HH:mm:ss"; });
- 新增序列化规则
- 添加之后的症状
解决方案来源 https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-converters-how-to?view=netcore-3.0&pivots=dotnet-core-3-1#deserialize-inferred-types-to-object-properties(貌似5.0已经解决此问题)