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

C#中使用System.Text.Json序列化JSON为驼峰命名失败问题

问题根源

直接序列化JsonElement时,System.Text.Json不会应用你设置的属性命名策略——因为JsonElement是已经解析完成的JSON DOM节点,序列化它的时候只是原样输出原有结构,完全忽略PropertyNamingPolicy配置。

解决方案

方案1:转成强类型/匿名类型再序列化(适合简单结构)

先把JSON字符串反序列化为强类型对象或者匿名类型,再用驼峰策略序列化,最后转回JsonElement。这样命名策略会在序列化对象时生效:

用字典处理任意结构:

private static JsonElement SerializeWithCamelCase(string jsonContent)
{
    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true
    };

    // 反序列化为字典,让命名策略生效
    var dict = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonContent, options);
    var camelCaseJson = JsonSerializer.Serialize(dict, options);

    using var doc = JsonDocument.Parse(camelCaseJson);
    return doc.RootElement.Clone();
}

用强类型(结构固定时更推荐):

先定义对应模型:

public class DataModel
{
    public string Key { get; set; }
}

然后修改方法:

private static JsonElement SerializeWithCamelCase(string jsonContent)
{
    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true
    };

    var model = JsonSerializer.Deserialize<DataModel>(jsonContent, options);
    var camelCaseJson = JsonSerializer.Serialize(model, options);

    using var doc = JsonDocument.Parse(camelCaseJson);
    return doc.RootElement.Clone();
}

方案2:手动遍历DOM重命名属性(适合复杂嵌套结构)

如果JSON结构复杂(比如多层嵌套),可以手动遍历JsonElement的属性,将每个属性名转换为驼峰格式,再构建新的JsonElement:

private static JsonElement SerializeWithCamelCase(string jsonContent)
{
    using var originalDoc = JsonDocument.Parse(jsonContent);
    var root = originalDoc.RootElement;

    using var stream = new MemoryStream();
    using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });

    writer.WriteStartObject();
    foreach (var prop in root.EnumerateObject())
    {
        // 用内置驼峰策略转换属性名
        var camelCaseName = JsonNamingPolicy.CamelCase.ConvertName(prop.Name);
        writer.WritePropertyName(camelCaseName);
        // 原样写入属性值
        prop.Value.WriteTo(writer);
    }
    writer.WriteEndObject();
    writer.Flush();

    stream.Position = 0;
    using var camelCaseDoc = JsonDocument.Parse(stream);
    return camelCaseDoc.RootElement.Clone();
}
验证效果

调用上述任意方法后,得到的JsonElement对应的JSON输出都会符合预期:

{
    "key": "TextA"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:00:01