CamelCase只有在Json.Net中没有显式设置PropertyName时?

时间:2012-10-05 15:07:42

标签: c# json.net

我在我的网站上使用Json.Net。我希望序列化器默认在camelcase中序列化属性名称。我不希望它更改我手动分配的属性名称。我有以下代码:

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}

这可能实现吗?

2 个答案:

答案 0 :(得分:20)

您可以像这样覆盖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;
    }
}

答案 1 :(得分:1)

随着NamingStrategy的推出,它变得更容易 作为奖励,您可以不修改字典键。

class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    public MyContractResolver()
    {
        NamingStrategy.OverrideSpecifiedNames = false;    //Overriden
        NamingStrategy.ProcessDictionaryKeys = false;     //Overriden
        NamingStrategy.ProcessExtensionDataNames = false; //default
    }
}