我如何使用 Json.NET 驼峰式大小写特定的 属性?

How do I camel case a specific property using Json.NET?

我想使用 Json.NET 而不是所有属性来对对象的特定属性进行驼峰式大小写。

我有一个这样的对象:

class A {
    public object B { get; set; }
    public object C { get; set; } // this property should be camel cased
}

我希望它序列化为:

{ B: 1, c: 2 }

我遇到了 this post 关于骆驼外壳 all 属性无条件,这是使用:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JsonConvert.SerializeObject(a, settings);

但是我找不到针对特定 属性 的骆驼外壳的对应问题。这是怎么做到的?

您可以将 JsonPropertyAttribute's NamingStrategyType 应用于您想要驼峰式大小写的字段:

class A 
{
    [JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public object C { get; set; }
}

或者您可以直接指定 属性 的名称:

class A 
{
    [JsonProperty("c")]
    public object C { get; set; }
}