Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I customize Json.NET serialization without annotating my classes?

I need to serialize some entity classes to JSON, using Json.NET. In order to customize the names of the properties, I use the [JsonProperty] attribute like this:

    [JsonProperty("lastName")]
    public string LastName { get; set; }

The problem is, I'd prefer not to have any JSON-related attributes in my entities... Is there a way to externalize the annotations somehow, so that they don't clutter my entities?

Using XmlSerializer, it can be done easily with the XmlAttributeOverrides class. Is there something similar for Json.NET ?

like image 542
Thomas Levesque Avatar asked Aug 09 '12 09:08

Thomas Levesque


1 Answers

Yes, you can create a custom contract resolver and customize the JsonProperty definition without the use of attributes. Example follows:

class Person { public string First { get; set; } }

class PersonContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(
        MemberInfo member, 
        MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (member.DeclaringType == typeof(Person) && member.Name == "First")
        {
            property.PropertyName = "FirstName";
        }

        return property;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var result = JsonConvert.SerializeObject(
            new Person { First = "John" },
            new JsonSerializerSettings 
            { 
                ContractResolver = new PersonContractResolver() 
            });

        Console.WriteLine(result);
    }
}

This output of this sample program will be the following:

// {"FirstName":"John"}
like image 173
João Angelo Avatar answered Oct 04 '22 01:10

João Angelo