我希望能够使用CamelCasePropertyNameContractResolver,但需要针对特定属性名称进行覆盖。为此,我使用JsonProperty属性。这个方法很好用,但当我选择的名称全部大写时,它就无法正常工作了。有什么建议或解决方法吗?
在下面的示例中,当我不使用CamelCasePropertyNameContractResolver时,Bar被序列化为“BAR”,但当我使用解析器时,它被序列化为“bar”。Foo和CamelCaseProperty在两种情况下都被正确地序列化。
在下面的示例中,当我不使用CamelCasePropertyNameContractResolver时,Bar被序列化为“BAR”,但当我使用解析器时,它被序列化为“bar”。Foo和CamelCaseProperty在两种情况下都被正确地序列化。
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleTester
{
class Program
{
static void Main(string[] args)
{
var foo = new FooBar {CamelCaseProperty = "test", Foo = "test", Bar = "test" };
var output = JsonConvert.SerializeObject(foo);
// output "CamelCaseProperty", "fOO", "BAR"
var output2 = JsonConvert.SerializeObject(foo, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
// output "camelCaseProperty", "fOO", "bar"
}
}
public class FooBar
{
public string CamelCaseProperty { get; set; }
[JsonProperty("fOO")]
public string Foo { get; set; }
[JsonProperty("BAR")]
public string Bar { get; set; }
}
}
new CamelCasePropertyNamesContractResolver()
,而是使用new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }
。关于为什么,请参见这里。 - dbc