首页 新闻 会员 周边

netcore3.1 json反序列化日期格式全局设置

0
[已关闭问题] 关闭于 2020-05-08 13:58

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);
又沙又甜的主页 又沙又甜 | 初学一级 | 园豆:120
提问于:2020-05-08 11:32
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册