Click or drag to resize
Json.NETJsonConverterAttribute on a class
 

This sample uses the JsonConverterAttribute to specify that a JsonConverter should be used when serializing and deserializing a class.

Sample
Types
 1public class UserConverter : JsonConverter
 2{
 3    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 4    {
 5        User user = (User)value;
 6
 7        writer.WriteValue(user.UserName);
 8    }
 9
10    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
11    {
12        User user = new User();
13        user.UserName = (string)reader.Value;
14
15        return user;
16    }
17
18    public override bool CanConvert(Type objectType)
19    {
20        return objectType == typeof(User);
21    }
22}
23
24[JsonConverter(typeof(UserConverter))]
25public class User
26{
27    public string UserName { get; set; }
28}
Usage
1User user = new User
2{
3    UserName = @"domain\username"
4};
5
6string json = JsonConvert.SerializeObject(user, Formatting.Indented);
7
8Console.WriteLine(json);
9// "domain\\username"