本文介绍了仅当在Json.Net中未明确设置PropertyName时才使用CamelCase吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将Json.Net用于我的网站.我希望序列化程序默认情况下在驼峰式情况下序列化属性名称.我不希望它更改我手动分配的属性名称.我有以下代码:
I'm using Json.Net for my website. I want the serializer to serialize property names in camelcase by default. I don't want it to change property names that I manually assign. I have the following code:
public class TestClass
{
public string NormalProperty { get; set; }
[JsonProperty(PropertyName = "CustomName")]
public string ConfiguredProperty { get; set; }
}
public void Experiment()
{
var data = new TestClass { NormalProperty = null,
ConfiguredProperty = null };
var result = JsonConvert.SerializeObject(data,
Formatting.None,
new JsonSerializerSettings {ContractResolver
= new CamelCasePropertyNamesContractResolver()}
);
Console.Write(result);
}
Experiment
的输出是:
{"normalProperty":null,"customName":null}
但是,我希望输出为:
{"normalProperty":null,"CustomName":null}
这有可能实现吗?
推荐答案
您可以像这样覆盖CamelCasePropertyNamesContractResolver
类:
class CamelCase : CamelCasePropertyNamesContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member,
MemberSerialization memberSerialization)
{
var res = base.CreateProperty(member, memberSerialization);
var attrs = member
.GetCustomAttributes(typeof(JsonPropertyAttribute),true);
if (attrs.Any())
{
var attr = (attrs[0] as JsonPropertyAttribute);
if (res.PropertyName != null)
res.PropertyName = attr.PropertyName;
}
return res;
}
}
这篇关于仅当在Json.Net中未明确设置PropertyName时才使用CamelCase吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!