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

.NET Framework 4.8 C#项目:配置OpenAPI生成器使用System.Text.Json

实现方案

可以通过OpenAPI代码生成器的配置文件指定使用System.Text.Json作为序列化器,具体步骤如下:

1. 确保使用兼容的OpenAPI Generator版本

需要使用v6.0及以上版本的OpenAPI Generator,早期版本对System.Text.Json的支持不完善。

2. 配置生成器的JSON配置文件

在你的生成配置文件(例如openapi-generator.json)中,通过configOptions指定序列化库为system-text-json,并适配.NET Framework 4.8的特性:

{
  "generatorName": "csharp",
  "inputSpec": "./path/to/your/openapi.json",
  "outputDir": "./generated-client",
  "configOptions": {
    "targetFramework": "net48",
    "library": "system-text-json",
    "useSystemTextJson": true,
    "nullableReferenceTypes": false, // .NET Framework 4.8不支持可空引用类型,需禁用
    "packageName": "Your.Project.ApiClient",
    "packageVersion": "1.0.0"
  }
}

3. 生成代码并适配项目

  • 运行OpenAPI Generator命令生成代码(例如使用CLI:openapi-generator-cli generate -c openapi-generator.json)
  • 在你的.NET Framework 4.8项目中,安装System.Text.Json NuGet包(推荐安装6.x版本,适配.NET Framework 4.8)
  • 将生成的代码引入项目,检查生成的客户端类,确认序列化逻辑已使用System.Text.Json.JsonSerializer而非Newtonsoft.Json

注意事项

  • 如果生成的代码仍存在Newtonsoft.Json相关依赖,检查OpenAPI Generator版本是否符合要求,或确认配置中的library参数是否正确设置为system-text-json
  • .NET Framework 4.8对System.Text.Json的部分高级特性支持有限,若生成代码中出现兼容性问题,可能需要调整OpenAPI规范中的部分定义,或升级System.Text.Json到最新兼容版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 18:42:07