19

我正在为我的网站使用 Json.Net。我希望序列化程序默认以驼峰形式序列化属性名称。我不希望它更改我手动分配的属性名称。我有以下代码:

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}

这有可能实现吗?

4

2 回答 2

21

您可以像这样覆盖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;
    }
}
于 2012-10-08T10:54:09.017 回答
2

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

class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    public MyContractResolver()
    {
        NamingStrategy.OverrideSpecifiedNames = false;    //Overriden
        NamingStrategy.ProcessDictionaryKeys = false;     //Overriden
        NamingStrategy.ProcessExtensionDataNames = false; //default
    }
}
于 2018-05-22T12:05:57.573 回答