Click or drag to resize
Json.NETCustom JsonConverter
 

This sample creates a custom JsonConverter that overrides serialization to add a keys property.

Sample
Types
 1public class KeysJsonConverter : JsonConverter
 2{
 3    private readonly Type[] _types;
 4
 5    public KeysJsonConverter(params Type[] types)
 6    {
 7        _types = types;
 8    }
 9
10    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
11    {
12        JToken t = JToken.FromObject(value);
13
14        if (t.Type != JTokenType.Object)
15        {
16            t.WriteTo(writer);
17        }
18        else
19        {
20            JObject o = (JObject)t;
21            IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
22
23            o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
24
25            o.WriteTo(writer);
26        }
27    }
28
29    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
30    {
31        throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
32    }
33
34    public override bool CanRead
35    {
36        get { return false; }
37    }
38
39    public override bool CanConvert(Type objectType)
40    {
41        return _types.Any(t => t == objectType);
42    }
43}
44
45public class Employee
46{
47    public string FirstName { get; set; }
48    public string LastName { get; set; }
49    public IList<string> Roles { get; set; }
50}
Usage
 1Employee employee = new Employee
 2{
 3    FirstName = "James",
 4    LastName = "Newton-King",
 5    Roles = new List<string>
 6    {
 7        "Admin"
 8    }
 9};
10
11string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new KeysJsonConverter(typeof(Employee)));
12
13Console.WriteLine(json);
14// {
15//   "Keys": [
16//     "FirstName",
17//     "LastName",
18//     "Roles"
19//   ],
20//   "FirstName": "James",
21//   "LastName": "Newton-King",
22//   "Roles": [
23//     "Admin"
24//   ]
25// }
26
27Employee newEmployee = JsonConvert.DeserializeObject<Employee>(json, new KeysJsonConverter(typeof(Employee)));
28
29Console.WriteLine(newEmployee.FirstName);
30// James