Click or drag to resize
Json.NETSerialization Callback Attributes
 

This sample uses serialization callback attributes (OnSerializingAttribute, OnSerializedAttribute, OnDeserializingAttribute, OnDeserializedAttribute) to manipulate an object before and after its serialization and deserialization.

Sample
Types
 1public class SerializationEventTestObject
 2{
 3    // 2222
 4    // This member is serialized and deserialized with no change.
 5    public int Member1 { get; set; }
 6
 7    // The value of this field is set and reset during and 
 8    // after serialization.
 9    public string Member2 { get; set; }
10
11    // This field is not serialized. The OnDeserializedAttribute 
12    // is used to set the member value after serialization.
13    [JsonIgnore]
14    public string Member3 { get; set; }
15
16    // This field is set to null, but populated after deserialization.
17    public string Member4 { get; set; }
18
19    public SerializationEventTestObject()
20    {
21        Member1 = 11;
22        Member2 = "Hello World!";
23        Member3 = "This is a nonserialized value";
24        Member4 = null;
25    }
26
27    [OnSerializing]
28    internal void OnSerializingMethod(StreamingContext context)
29    {
30        Member2 = "This value went into the data file during serialization.";
31    }
32
33    [OnSerialized]
34    internal void OnSerializedMethod(StreamingContext context)
35    {
36        Member2 = "This value was reset after serialization.";
37    }
38
39    [OnDeserializing]
40    internal void OnDeserializingMethod(StreamingContext context)
41    {
42        Member3 = "This value was set during deserialization";
43    }
44
45    [OnDeserialized]
46    internal void OnDeserializedMethod(StreamingContext context)
47    {
48        Member4 = "This value was set after deserialization.";
49    }
50}
Usage
 1SerializationEventTestObject obj = new SerializationEventTestObject();
 2
 3Console.WriteLine(obj.Member1);
 4// 11
 5Console.WriteLine(obj.Member2);
 6// Hello World!
 7Console.WriteLine(obj.Member3);
 8// This is a nonserialized value
 9Console.WriteLine(obj.Member4);
10// null
11
12string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
13// {
14//   "Member1": 11,
15//   "Member2": "This value went into the data file during serialization.",
16//   "Member4": null
17// }
18
19Console.WriteLine(obj.Member1);
20// 11
21Console.WriteLine(obj.Member2);
22// This value was reset after serialization.
23Console.WriteLine(obj.Member3);
24// This is a nonserialized value
25Console.WriteLine(obj.Member4);
26// null
27
28obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
29
30Console.WriteLine(obj.Member1);
31// 11
32Console.WriteLine(obj.Member2);
33// This value went into the data file during serialization.
34Console.WriteLine(obj.Member3);
35// This value was set during deserialization
36Console.WriteLine(obj.Member4);
37// This value was set after deserialization.