Click or drag to resize
Json.NETSerialization using ContractResolver
 

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON without placing attributes on your classes.

Anything that can be set on an object, collection, property, etc, using attributes or methods to control serialization can also be set using an IContractResolver.

DefaultContractResolver

The DefaultContractResolver is the default resolver used by the serializer. It provides many avenues of extensibility in the form of virtual methods that can be overriden.

CamelCasePropertyNamesContractResolver

CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase.

ContractResolver
 1Product product = new Product
 2{
 3    ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
 4    Name = "Widget",
 5    Price = 9.99m,
 6    Sizes = new[] { "Small", "Medium", "Large" }
 7};
 8
 9string json =
10    JsonConvert.SerializeObject(
11        product,
12        Formatting.Indented,
13        new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
14        );
15
16//{
17//  "name": "Widget",
18//  "expiryDate": "2010-12-20T18:01Z",
19//  "price": 9.99,
20//  "sizes": [
21//    "Small",
22//    "Medium",
23//    "Large"
24//  ]
25//}
Custom IContractResolver Examples
Use JsonConverter with IContractResolver
 1public class ConverterContractResolver : DefaultContractResolver
 2{
 3    public new static readonly ConverterContractResolver Instance = new ConverterContractResolver();
 4
 5    protected override JsonContract CreateContract(Type objectType)
 6    {
 7        JsonContract contract = base.CreateContract(objectType);
 8
 9        // this will only be called once and then cached
10        if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset))
11            contract.Converter = new JavaScriptDateTimeConverter();
12
13        return contract;
14    }
15}

This example sets a JsonConverter for a type using an IContractResolver. Using a contract resolver here is useful because DateTime is not your own type and it is not possible to place a JsonConverterAttribute on it.

Conditional properties with IContractResolver
 1public class ShouldSerializeContractResolver : DefaultContractResolver
 2{
 3    public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
 4
 5    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
 6    {
 7        JsonProperty property = base.CreateProperty(member, memberSerialization);
 8
 9        if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
10        {
11            property.ShouldSerialize =
12                instance =>
13                {
14                    Employee e = (Employee)instance;
15                    return e.Manager != e;
16                };
17        }
18
19        return property;
20    }
21}

This example sets up conditional serialization for a property using an IContractResolver. This is useful if you want to conditionally serialize a property but don't want to add additional methods to your type.

See Also