Oliver
Oliver

Reputation: 11607

CamelCase only if PropertyName not explicitly set in 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);
}

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?

Upvotes: 19

Views: 9642

Answers (2)

hultqvist
hultqvist

Reputation: 18461

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

Upvotes: 2

Oliver
Oliver

Reputation: 11607

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

Upvotes: 21

Related Questions