This repository has been archived on 2023-02-13. You can view files and clone it, but cannot push or open issues or pull requests.
gswi-server/gswi/JSONConverter/JsonCreationConverter.cs

54 lines
1.4 KiB
C#
Raw Normal View History

2022-02-20 19:04:11 +01:00
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
namespace gswi.JSONConverter
{
public abstract class JsonCreationConverter<T> : 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)
{
}
}
}