using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NLog; namespace gswi.JSONConverter { public abstract class JsonCreationConverter : JsonConverter { static Logger _logger = LogManager.GetCurrentClassLogger(); protected abstract T Create(Type objectType, JObject jObject); public override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } public override bool CanWrite { get { return false; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { // Load JObject from stream JObject jObject = JObject.Load(reader); // Create target object based on JObject T target = Create(objectType, jObject); // Populate the object properties serializer.Populate(jObject.CreateReader(), target); return target; } catch (Exception e) { _logger.Error(e); return null; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } } }