CamelCase only if PropertyName not explicitly set in Json.Net?

安稳与你 提交于 2019-12-12 10:28:35

问题


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);
}

The output from Experiment is:

{"normalProperty":null,"customName":null}

However, I want the output to be:

{"normalProperty":null,"CustomName":null}

Is this possible to achieve?


回答1:


You can override the CamelCasePropertyNamesContractResolver class like this:

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;
    }
}



回答2:


With the introduction of NamingStrategy it's easier.
As a bonus you can get it to not modify dictionary keys.

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


来源:https://stackoverflow.com/questions/12749046/camelcase-only-if-propertyname-not-explicitly-set-in-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!