IContractResolver Interface
Click or drag to resize
Json.NET

IContractResolver Interface

 
Used by JsonSerializer to resolve a JsonContract for a given Type.

Namespace:  Newtonsoft.Json.Serialization
Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 11.0.1
Syntax
C#
public interface IContractResolver

The IContractResolver type exposes the following members.

Methods
  NameDescription
Public methodResolveContract
Resolves the contract for a given type.
Top
Examples
IContractResolver Class
public class DynamicContractResolver : DefaultContractResolver
{
    private readonly char _startingWithChar;

    public DynamicContractResolver(char startingWithChar)
    {
        _startingWithChar = startingWithChar;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        // only serializer properties that start with the specified character
        properties =
            properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();

        return properties;
    }
}

public class Book
{
    public string BookName { get; set; }
    public decimal BookPrice { get; set; }
    public string AuthorName { get; set; }
    public int AuthorAge { get; set; }
    public string AuthorCountry { get; set; }
}
IContractResolver Example
Book book = new Book
{
    BookName = "The Gathering Storm",
    BookPrice = 16.19m,
    AuthorName = "Brandon Sanderson",
    AuthorAge = 34,
    AuthorCountry = "United States of America"
};

string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });

// {
//   "AuthorName": "Brandon Sanderson",
//   "AuthorAge": 34,
//   "AuthorCountry": "United States of America"
// }

string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });

// {
//   "BookName": "The Gathering Storm",
//   "BookPrice": 16.19
// }
See Also