NJsonSchema生成C#代码时生成泛型对象而非指定类的问题
NJsonSchema生成C#类时未识别Schema的patternProperties结构问题
问题场景
使用NJsonSchema处理一份第三方定义、无法修改的JSON Schema,需要生成能输出符合该Schema的C#类,但工具仅生成了泛型object类型的字典,未生成Schema中定义的具体字段和强类型类。
生成器代码
var schema = JsonSchema.FromFileAsync(@"../../../SchemaSnippets.json"); CSharpGeneratorSettings set = new CSharpGeneratorSettings(); set.Namespace = "EPJSON"; set.SchemaType = SchemaType.JsonSchema; set.GenerateDataAnnotations = true; set.AnyType = "object"; set.ClassStyle = CSharpClassStyle.Poco; set.HandleReferences = false; var generator = new CSharpGenerator(schema.Result, set); var file = generator.GenerateFile(); File.WriteAllText(@"../../../SchemaSnippetsCode.cs", file);
目标Schema片段
{ "$schema": "https://json-schema.org/draft-07/schema#", "properties": { "Version": { "patternProperties": { ".*": { "type": "object", "properties": { "version_identifier": { "type": "string", "default": "22.2" } } } }, "group": "Simulation Parameters", "legacy_idd": { "field_info": { "version_identifier": { "field_name": "Version Identifier", "field_type": "a" } }, "fields": [ "version_identifier" ], "alphas": { "fields": [ "version_identifier" ] }, "numerics": { "fields": [] } }, "type": "object", "maxProperties": 1, "memo": "Specifies the EnergyPlus version of the IDF file.", "format": "singleLine" } } }
当前生成的C#代码
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.8.0.0 (Newtonsoft.Json v9.0.0.0)")] [Newtonsoft.Json.JsonProperty("Version", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, object> Version { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties; [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary<string, object>()); } set { _additionalProperties = value; } }
期望生成的C#代码
public System.Collections.Generic.IDictionary<string, VersionObject> Version { get; set; } class VersionObject { string version_identifier { get; set; } = "22.2"; }
解决方案
1. 启用PatternProperties类生成选项
NJsonSchema默认不会为patternProperties中的子结构生成强类型类,需要在生成器设置中开启GeneratePatternPropertiesAsClasses选项:
var set = new CSharpGeneratorSettings(); set.Namespace = "EPJSON"; set.SchemaType = SchemaType.JsonSchema; set.GenerateDataAnnotations = true; set.AnyType = "object"; set.ClassStyle = CSharpClassStyle.Poco; set.HandleReferences = false; // 关键配置:开启patternProperties的强类型类生成 set.GeneratePatternPropertiesAsClasses = true;
2. 升级NJsonSchema版本(可选)
你当前使用的是10.8.0版本,该版本对patternProperties的支持可能存在局限性。建议升级到最新稳定版,能更好地处理这类动态键的Schema结构。
效果验证
修改配置后重新生成,NJsonSchema会为patternProperties中匹配任意键的子对象生成对应的VersionObject类,并将Version属性的字典类型改为IDictionary<string, VersionObject>,与你期望的代码结构一致。
内容的提问来源于stack exchange,提问作者timkado
相关产品推荐
相关产品推荐

