Click or drag to resize
Json.NETTypeNameHandling setting
 

This sample uses the TypeNameHandling setting to include type information when serializing JSON and read type information so that the create types are created when deserializing JSON.

Sample
Types
 1public abstract class Business
 2{
 3    public string Name { get; set; }
 4}
 5
 6public class Hotel : Business
 7{
 8    public int Stars { get; set; }
 9}
10
11public class Stockholder
12{
13    public string FullName { get; set; }
14    public IList<Business> Businesses { get; set; }
15}
Usage
 1Stockholder stockholder = new Stockholder
 2{
 3    FullName = "Steve Stockholder",
 4    Businesses = new List<Business>
 5    {
 6        new Hotel
 7        {
 8            Name = "Hudson Hotel",
 9            Stars = 4
10        }
11    }
12};
13
14string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
15{
16    TypeNameHandling = TypeNameHandling.All
17});
18
19Console.WriteLine(jsonTypeNameAll);
20// {
21//   "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
22//   "FullName": "Steve Stockholder",
23//   "Businesses": {
24//     "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
25//     "$values": [
26//       {
27//         "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
28//         "Stars": 4,
29//         "Name": "Hudson Hotel"
30//       }
31//     ]
32//   }
33// }
34
35string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
36{
37    TypeNameHandling = TypeNameHandling.Auto
38});
39
40Console.WriteLine(jsonTypeNameAuto);
41// {
42//   "FullName": "Steve Stockholder",
43//   "Businesses": [
44//     {
45//       "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
46//       "Stars": 4,
47//       "Name": "Hudson Hotel"
48//     }
49//   ]
50// }
51
52// for security TypeNameHandling is required when deserializing
53Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto, new JsonSerializerSettings
54{
55    TypeNameHandling = TypeNameHandling.Auto
56});
57
58Console.WriteLine(newStockholder.Businesses[0].GetType().Name);
59// Hotel