ConfigureServices:
services.AddControllers ().AddJsonOptions (options => {
options.JsonSerializerOptions.Converters.Add (new DateTimeConverter ());
options.JsonSerializerOptions.Converters.Add (new DateTimeNullableConverter ());
}).SetCompatibilityVersion (CompatibilityVersion.Latest);
public class DateTimeConverter : 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"));
}
}
在ConfigureServices方法中有对json中日期类型栏位格式化,但反序列化时,并未生效,这什么原因?
string json = "{\"ID\":\"3b025ea5-12c7-4095-b787-b87901edb249\",\"RuleSeq\":1,\"BillTo\":\"1\",\"InvoiceParty\":\"1\",\"Title\":\"3\",\"UpdateDate\":\"2020-05-07 16:17:41\"}";
var result = JsonSerializer.Deserialize<BdBillToRule>(json);
error:
最里面的异常 System.FormatException : The JSON value is not in a supported DateTime format.
这样使用时没问题的:
var jsonOptions = new JsonSerializerOptions();
jsonOptions.Converters.Add(new DateTimeConverter ());
var result = JsonSerializer.Deserialize<BdBillToRule>(json, jsonOptions);