Click or drag to resize
Json.NETIContractResolver Interface
 
Used by JsonSerializer to resolves a JsonContract for a given Type.

Namespace: Newtonsoft.Json.Serialization
Assembly: Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 7.0.0.0 (7.0.1.18129)
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
 1public class DynamicContractResolver : DefaultContractResolver
 2{
 3    private readonly char _startingWithChar;
 4
 5    public DynamicContractResolver(char startingWithChar)
 6    {
 7        _startingWithChar = startingWithChar;
 8    }
 9
10    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
11    {
12        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
13
14        // only serializer properties that start with the specified character
15        properties =
16            properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
17
18        return properties;
19    }
20}
21
22public class Book
23{
24    public string BookName { get; set; }
25    public decimal BookPrice { get; set; }
26    public string AuthorName { get; set; }
27    public int AuthorAge { get; set; }
28    public string AuthorCountry { get; set; }
29}
IContractResolver Example
 1Book book = new Book
 2{
 3    BookName = "The Gathering Storm",
 4    BookPrice = 16.19m,
 5    AuthorName = "Brandon Sanderson",
 6    AuthorAge = 34,
 7    AuthorCountry = "United States of America"
 8};
 9
10string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
11    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
12
13// {
14//   "AuthorName": "Brandon Sanderson",
15//   "AuthorAge": 34,
16//   "AuthorCountry": "United States of America"
17// }
18
19string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
20    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
21
22// {
23//   "BookName": "The Gathering Storm",
24//   "BookPrice": 16.19
25// }
See Also