JSON转C#时遇‘default’关键字冲突的解决方法咨询
解决ADP JSON Schema中
default关键字与C#字段名冲突的问题 针对你遇到的ADP JSON Schema里default字段转C#时被识别为关键字的问题,有两种靠谱的解决方案,我分别给你拆解下:
方案1:用属性+关键字转义保留字段映射
C#允许通过@符号转义关键字,让编译器把它当作普通标识符,再配合序列化属性指定JSON字段名,完美解决冲突。
如果你用的是System.Text.Json(.NET Core 3.0+ 默认序列化库),可以这样写:
public class NoteIndicator { [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("type")] public string Type { get; set; } [JsonPropertyName("optional")] public bool Optional { get; set; } // 用@转义关键字,同时指定JSON对应的键是"default" [JsonPropertyName("default")] public bool @default { get; set; } }
如果用的是Newtonsoft.Json(Json.NET),把JsonPropertyName换成JsonProperty就行:
public class NoteIndicator { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("optional")] public bool Optional { get; set; } [JsonProperty("default")] public bool @default { get; set; } }
这样既保留了JSON里的default字段名,又让C#编译器正确识别这个字段,序列化/反序列化完全不受影响。
方案2:修改JSON Schema中的default字段名
如果你的场景允许(比如你能控制Schema的生成,或者ADP的API接受修改后的字段名),直接把Schema里的default改成defaultValue这类非关键字名称是更简洁的选择。比如:
"noteIndicator" : { "description" : "True indicates that the System of Record supports the user entering notes / comments. If the value is false then the notes / comments field will not be visible in the UI", "type" : "boolean", "optional" : true, "defaultValue" : false }
之后转C#时就不会有关键字冲突问题了。但要注意:如果这是ADP官方提供的Schema,API返回的JSON里确实是default键,那修改字段名会导致反序列化失败,这种情况下就不能用这个方案。
总结
- 必须和ADP官方JSON结构保持一致?优先选方案1,用属性+@转义的方式。
- 可以自主调整Schema且不影响API交互?方案2更省心。
内容的提问来源于stack exchange,提问作者Shane Sepac
相关产品推荐
相关产品推荐

