Click or drag to resize
Json.NETCustom IContractResolver
 

This sample creates a custom IContractResolver that only serializes a type's properties that begin with a specified character.

Sample
Types
 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 Person
23{
24    public string FirstName { get; set; }
25    public string LastName { get; set; }
26
27    public string FullName
28    {
29        get { return FirstName + " " + LastName; }
30    }
31}
Usage
 1Person person = new Person
 2{
 3    FirstName = "Dennis",
 4    LastName = "Deepwater-Diver"
 5};
 6
 7string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
 8    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
 9
10Console.WriteLine(startingWithF);
11// {
12//   "FirstName": "Dennis",
13//   "FullName": "Dennis Deepwater-Diver"
14// }
15
16string startingWithL = JsonConvert.SerializeObject(person, Formatting.Indented,
17    new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('L') });
18
19Console.WriteLine(startingWithL);
20// {
21//   "LastName": "Deepwater-Diver"
22// }