Click or drag to resize
Json.NETDeserialize ExtensionData
 

This sample deserializes JSON to an object with extension data.

Sample
Types
 1public class DirectoryAccount
 2{
 3    // normal deserialization
 4    public string DisplayName { get; set; }
 5
 6    // these properties are set in OnDeserialized
 7    public string UserName { get; set; }
 8    public string Domain { get; set; }
 9
10    [JsonExtensionData]
11    private IDictionary<string, JToken> _additionalData;
12
13    [OnDeserialized]
14    private void OnDeserialized(StreamingContext context)
15    {
16        // SAMAccountName is not deserialized to any property
17        // and so it is added to the extension data dictionary
18        string samAccountName = (string)_additionalData["SAMAccountName"];
19
20        Domain = samAccountName.Split('\\')[0];
21        UserName = samAccountName.Split('\\')[1];
22    }
23
24    public DirectoryAccount()
25    {
26        _additionalData = new Dictionary<string, JToken>();
27    }
28}
Usage
 1string json = @"{
 2  'DisplayName': 'John Smith',
 3  'SAMAccountName': 'contoso\\johns'
 4}";
 5
 6DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);
 7
 8Console.WriteLine(account.DisplayName);
 9// John Smith
10
11Console.WriteLine(account.Domain);
12// contoso
13
14Console.WriteLine(account.UserName);
15// johns