使用Newtonsoft.Json在Net6中设置时间格式(含T/不含T)

实例一:       
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss.fff", }; Model model = new Model { CreatedAt = DateTime.UtcNow }; string json = JsonConvert.SerializeObject(model, Formatting.None, jsonSettings); Console.WriteLine(json);
    public class Model
    {
        public DateTime CreatedAt { get; set; }
    }

实例二:在net6中自定义

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 配置 JsonSerializerOptions
    app.UseJson(options =>
    {
        options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
        options.SerializerOptions.WriteIndented = true;
        options.SerializerOptions.Converters.Add(new DateTimeConverter("yyyy-MM-ddTHH:mm:ssZ"));
    });

    // 其他配置与中间件
    // ...
}
public class DateTimeConverter : JsonConverter<DateTime>
{
    private readonly string _dateFormat;

    public DateTimeConverter(string dateFormat)
    {
        _dateFormat = dateFormat;
    }

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String && DateTime.TryParseExact(reader.GetString(), _dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime dateTime))
        {
            return dateTime;
        }

        return default;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_dateFormat));
    }
}

 

posted @ 2023-04-03 17:29  Tammytan  阅读(1507)  评论(0编辑  收藏  举报