JsonCreationConverter.cs
1 using System;
2 using Newtonsoft.Json;
3 using Newtonsoft.Json.Linq;
4 
5 namespace Microsoft.Bot.Builder.Calling.ObjectModel.Misc
6 {
12  public abstract class JsonCreationConverter<T> : JsonConverter
13  {
17  protected abstract T Create(Type objectType, JObject jsonObject);
18 
22  public override bool CanConvert(Type objectType)
23  {
24  return typeof(T).IsAssignableFrom(objectType);
25  }
26 
30  public override bool CanWrite
31  {
32  get
33  {
34  return false;
35  }
36  }
37 
44  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
45  {
46  if (reader.TokenType == JsonToken.Null)
47  return null;
48 
49  // Load JObject from stream
50  JObject jObject = JObject.Load(reader);
51 
52  // Create target object based on JObject
53  T target = Create(objectType, jObject);
54 
55  //Create a new reader for this jObject, and set all properties to match the original reader.
56  JsonReader jObjectReader = jObject.CreateReader();
57  jObjectReader.Culture = reader.Culture;
58  jObjectReader.DateParseHandling = reader.DateParseHandling;
59  jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
60  jObjectReader.FloatParseHandling = reader.FloatParseHandling;
61 
62  // Populate the object properties
63  serializer.Populate(jObjectReader, target);
64 
65  return target;
66  }
67 
72  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
73  {
74  serializer.Serialize(writer, value);
75  }
76  }
77 }
Helper class to use for deserializing where the concrete classes are determined by checking propertie...
override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
Serializes to the specified type
override bool CanConvert(Type objectType)
Determines if this converted is designed to deserialization to objects of the specified type...
override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
Parses the json to the specified type.