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

使用CSharpGenerator无法生成C#类的问题排查

NSwag CSharpGenerator生成C#类仅输出命名空间问题

问题详情

我有如下JSON Schema:

{"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "ghkvhjhvh","title": "gffghfjhg","description": "zzzzzx","type": "object","properties": {"wbNumber": {"description": "fjhgfhg ","type": "string"},"documents": {"description": "ghfcg","type": "object","properties": {"documentType": {"description": "sdzfdgfxhg","type": "integer"},"file": {"description": "gdxfghfhgj","type": "string","contentEncoding": "base64"},"fileName": {"description": "dgfrhg","type": "string"}},"required": [ "documentType", "file", "fileName" ]}},"required": [ "wbNumber", "documents" ]}

尝试用NSwag的CSharpGenerator生成对应的C#类,代码如下:

var json = File.ReadAllText(schemaDestination);
var schema = await JsonSchema.FromJsonAsync(json);

var genSettings = new CSharpGeneratorSettings
{
    ClassStyle = CSharpClassStyle.Poco,
    JsonLibrary = CSharpJsonLibrary.SystemTextJson,
};

var generator = new CSharpGenerator(schema, genSettings);
var res = generator.GenerateFile();

await File.WriteAllTextAsync($"{destinationDir}/{Path.GetFileNameWithoutExtension(schemaDestination)
    .Humanize().Pascalize()}.cs", res);

已确认schema变量已正确加载并包含Schema的实际值,但最终生成的文件仅包含命名空间和System引用,无实际类定义,生成内容如下:

// <auto-generated>
//     Generated using the NSwag toolchain v11.0.0.0 (Newtonsoft.Json v13.0.0.0) (http://NSwag.org)
// </auto-generated>
//----------------------
namespace BusMesssage
{
    using System = global::System;
}

请问哪里操作有误?

解决方案

1. 升级NSwag版本

你使用的NSwag v11.0.0.0对JSON Schema Draft 2020-12规范支持不完善,该版本发布时Draft 2020-12尚未成为稳定标准。建议直接升级到v13.0.0及以上版本,新版本对Draft 2020-12有完整解析支持。

2. 显式指定根类配置

旧版本NSwag可能无法自动从Schema的title字段推断根类名称,可在生成设置中手动指定:

var genSettings = new CSharpGeneratorSettings
{
    ClassStyle = CSharpClassStyle.Poco,
    JsonLibrary = CSharpJsonLibrary.SystemTextJson,
    GenerateRootClasses = true,
    RootClass = "Gffghfjhg" // 可使用Schema的title值或自定义类名
};

3. 验证Schema加载方法

确保使用正确的命名空间下的Schema加载方法,新版本NSwag应使用NJsonSchema.JsonSchema.FromJsonAsync,避免因命名空间错误导致Schema信息丢失。

4. 临时降级Schema规范(若无法升级NSwag)

将JSON Schema的$schema字段改为旧版本规范,比如Draft 2019-09或Draft 7,旧版NSwag对这些规范的兼容性更好:

"$schema": "https://json-schema.org/draft/2019-09/schema"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:17:27