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

如何在ServiceStack模型绑定中定义JSON属性

ServiceStack 实现属性名与蛇形JSON键映射的方案

针对你遇到的帕斯卡命名属性匹配蛇形JSON键的需求,ServiceStack 提供了几种替代 Newtonsoft.Json [JsonProperty] 的方案:

  • 使用[DataMember(Name = "xxx")]属性
    这是 ServiceStack 推荐的原生方式,基于WCF的数据契约特性,示例代码如下:
using System.Runtime.Serialization;

public class Order
{
    [DataMember(Name = "order_number")]
    public int OrderNumber { get; set; }
}
  • 兼容 Newtonsoft.Json 的[JsonProperty]属性
    ServiceStack.Text 序列化器直接支持 Newtonsoft 的[JsonProperty]属性,如果你已经熟悉这种写法,可以直接沿用(需确保项目引用了 Newtonsoft.Json 包):
using Newtonsoft.Json;

public class Order
{
    [JsonProperty("order_number")]
    public int OrderNumber { get; set; }
}
  • 全局自动转换命名风格
    如果你的项目中有大量属性需要蛇形命名映射,可以全局配置序列化规则,避免逐个添加属性:
// 在应用初始化阶段配置
ServiceStack.Text.JsConfig.Init(new ServiceStack.Text.JsConfig {
    TextCase = ServiceStack.Text.TextCase.SnakeCase
});

配置后,所有帕斯卡命名的属性会自动与蛇形命名的JSON键双向映射,无需手动指定每个属性的对应关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:54:27