Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 621
Oliver Avatar asked Oct 05 '12 15:10

Oliver


People also ask

How does the JsonProperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Camelcasepropertconamescontractresolver?

CamelCasePropertyNamesContractResolver Class. Resolves member mappings for a type, camel casing property names.


1 Answers

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;
    }
}
like image 193
Oliver Avatar answered Sep 18 '22 06:09

Oliver