You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Quartz.NET 3.7.0使用System.Text.Json替代Newtonsoft.Json?

问题:Quartz.NET 3.7.0 配置使用 System.Text.Json 替代 Newtonsoft.Json

我正在使用基于.NET 7(.NET Core)的项目,采用Quartz.NET 3.7.0。项目已配置如下JSON转换器,在API中运行正常:

builder.Services.AddControllers(options =>
    {
       //...
    })
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new StringIdConverter());
        options.JsonSerializerOptions.Converters.Add(new UshortIdConverter());
    });

这些转换器负责将各类对象ID转换为字符串或整数。

我按如下方式注册Quartz:

services.AddQuartz(q =>
{
    q.SetProperty("quartz.serializer.type", "json");
    q.UsePersistentStore(p =>
    {
        p.UseMySql(Environment.GetEnvironmentVariable("MYSQL_CONNECTION_STRING"));
    });
});

// ASP.NET Core hosting
services.AddQuartzServer(options =>
{
    options.AwaitApplicationStarted = true;
    // 关闭时等待作业优雅完成
    options.WaitForJobsToComplete = true;
});

但作业执行时出现异常:

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Common.Domain.Identity.UnitId.

我发现Quartz默认使用Newtonsoft.Json,希望改用System.Text.Json序列化器,且已安装包含System.Text.Json相关功能的Quartz.Serialization包。请问如何配置Quartz以使用System.Text.Json而非Newtonsoft.Json?


解决方案

要让Quartz.NET切换到System.Text.Json序列化,需完成以下配置:

  1. 确认安装对应NuGet包
    确保已安装Quartz.Serialization.SystemTextJson包,这是Quartz官方提供的System.Text.Json序列化实现。

  2. 修改Quartz注册代码
    移除原有的quartz.serializer.type配置,改用扩展方法指定System.Text.Json序列化器,同时同步添加项目中自定义的JSON转换器:

services.AddQuartz(q =>
{
    // 配置使用System.Text.Json序列化器
    q.UseSystemTextJsonSerializer(options =>
    {
        // 添加项目中自定义的ID转换器
        options.Converters.Add(new StringIdConverter());
        options.Converters.Add(new UshortIdConverter());
        // 可按需添加其他System.Text.Json配置,例如:
        // options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        // options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

    q.UsePersistentStore(p =>
    {
        p.UseMySql(Environment.GetEnvironmentVariable("MYSQL_CONNECTION_STRING"));
    });
});

// ASP.NET Core hosting配置保持不变
services.AddQuartzServer(options =>
{
    options.AwaitApplicationStarted = true;
    options.WaitForJobsToComplete = true;
});
  1. 关键注意点
    • UseSystemTextJsonSerializer是Quartz.NET 3.x提供的扩展方法,用于替换默认的Newtonsoft.Json序列化器。
    • 序列化器配置必须放在UsePersistentStore之前,确保持久化存储使用指定的序列化逻辑。
    • 同步API中使用的自定义转换器,保证作业数据的序列化/反序列化逻辑和API一致,避免类型转换异常。

内容的提问来源于stack exchange,提问作者user826988

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:56:13