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

如何将带JsonProperty特性的User类按JSON属性名保存到Cosmos DB?

解决Cosmos DB保存文档时使用指定JSON属性名的问题

问题根源

你定义的[JsonProperty]是Newtonsoft.Json(Json.NET)的序列化特性,但Azure Cosmos DB SDK默认使用System.Text.Json处理序列化,因此该特性无法被识别,导致保存的文档仍使用类属性名。

两种简便实现方法

方法一:让Cosmos SDK使用Newtonsoft.Json序列化

在初始化CosmosClient时,配置自定义序列化器为NewtonsoftJsonSerializer,这样SDK就能识别你定义的[JsonProperty]特性:

// 初始化CosmosClient时添加配置
var cosmosClientOptions = new CosmosClientOptions
{
    Serializer = new NewtonsoftJsonSerializer(
        new JsonSerializerSettings
        {
            // 可选:如果需要默认驼峰命名可保留,已手动指定PropertyName的话可忽略此配置
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        }
    )
};

var _client = new CosmosClient(yourConnectionString, cosmosClientOptions);

方法二:改用System.Text.Json的特性替换Newtonsoft.Json特性

直接将[JsonProperty]替换为System.Text.Json的[JsonPropertyName]特性,无需修改SDK配置,默认序列化器即可识别:

using System.Text.Json.Serialization;

public class User
{
    [JsonPropertyName("id")]
    public string Id { get; set; }

    [JsonPropertyName("pk")]
    public string Pk { get; set; }

    [JsonPropertyName("phoneNumber")]
    public string PhoneNumber { get; set; }

    // 若希望CreatedAt的JSON键也自定义,同样添加特性
    [JsonPropertyName("createdAt")]
    public string CreatedAt { get; set; }
}

方法选择建议

  • 如果项目中已经大量使用Newtonsoft.Json,优先选方法一,无需修改实体类代码;
  • 若想依赖.NET原生的System.Text.Json,选方法二更轻量,避免引入额外依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:30:09