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

如何从XSD生成带JSON特性的POCO,解决小驼峰JSON序列化问题?

解决XSD生成POCO序列化JSON时大驼峰转小驼峰的无手动操作方案

针对你遇到的问题——XSD生成的大驼峰POCO在序列化JSON时需要转成小驼峰,且不想手动添加JsonProperty特性避免重新生成丢失——这里有几个无需手动干预的可行方案:

方案1:使用JSON序列化库的全局驼峰命名配置(推荐)

不管你用的是Newtonsoft.Json(Json.NET)还是.NET Core/5+自带的System.Text.Json,都可以通过全局配置实现自动转换,完全不需要修改生成的POCO代码。

对于Newtonsoft.Json:

在序列化时指定CamelCasePropertyNamesContractResolver,它会自动将大驼峰属性名转为小驼峰:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

// 初始化序列化配置
var serializerSettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    // 可选:保留空值、格式化输出等其他配置
    NullValueHandling = NullValueHandling.Ignore,
    Formatting = Formatting.Indented
};

// 序列化POCO为小驼峰JSON
var jsonString = JsonConvert.SerializeObject(yourGeneratedPocoInstance, serializerSettings);

对于System.Text.Json:

设置JsonSerializerOptions的PropertyNamingPolicy为驼峰命名策略即可:

using System.Text.Json;

var serializerOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true // 可选:格式化输出
};

var jsonString = JsonSerializer.Serialize(yourGeneratedPocoInstance, serializerOptions);

优点:完全不修改生成的POCO,XSD变更重新生成后无需任何额外操作,配置一次全局生效。

方案2:用支持自定义命名风格的XSD转POCO工具替代xsd.exe

如果你愿意换用更灵活的工具,可以试试Xsd2Code(开源免费),它支持生成POCO时直接配置命名风格和自动添加JsonProperty特性:

  1. 下载并打开Xsd2Code工具;
  2. 导入你的XSD文件;
  3. 在生成设置中,选择“Serialization”为Json.NET,然后将“Property Name Style”设置为CamelCase;
  4. 生成POCO,此时每个属性会自动带上[JsonProperty("小写驼峰名称")]特性,序列化时直接按小驼峰输出,且重新生成XSD时会保留这个配置。

优点:生成的POCO自带序列化特性,无需额外配置序列化器;适合需要直接看到特性定义的场景。

方案3:自动批量修改xsd.exe生成的POCO代码

如果你坚持要用xsd.exe,可以写一个简单的脚本或工具,在生成POCO后自动批量添加JsonProperty特性:
比如用PowerShell脚本,通过正则匹配大驼峰属性并替换:

$files = Get-ChildItem -Path "你的POCO代码目录" -Filter "*.cs" -Recurse

foreach ($file in $files) {
    $content = Get-Content $file.FullName -Raw
    # 匹配 public [类型] [大驼峰属性名] { get; set; } 的格式
    $newContent = [regex]::Replace($content, 'public\s+(\w+)\s+([A-Z][a-zA-Z0-9]+)\s+\{ get; set; \}', {
        param($match)
        $type = $match.Groups[1].Value
        $propertyName = $match.Groups[2].Value
        # 转小驼峰:首字母小写
        $camelCaseName = $propertyName.Substring(0,1).ToLower() + $propertyName.Substring(1)
        return "[JsonProperty(`"$camelCaseName`")] public $type $propertyName { get; set; }"
    })
    # 自动添加Newtonsoft.Json引用
    if (-not $newContent.Contains("using Newtonsoft.Json;")) {
        $newContent = "using Newtonsoft.Json;" + [Environment]::NewLine + $newContent
    }
    Set-Content $file.FullName -Value $newContent -Encoding UTF8
}

优点:保留使用xsd.exe的习惯,自动完成特性添加;缺点是需要维护脚本,处理特殊命名(比如缩写、全大写属性)时可能需要调整正则。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:31:10