42 lines
1.3 KiB
C#
42 lines
1.3 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using eSuite.Core.Miscellaneous;
|
|
|
|
namespace e_suite.Modules.WorkflowTemplatesManager.Repository;
|
|
|
|
public class GeneralIdRefConverter<T> : JsonConverter<T>
|
|
{
|
|
private readonly Func<GeneralIdRef, T?> _lookup;
|
|
|
|
public GeneralIdRefConverter(Func<GeneralIdRef, T?> lookup)
|
|
{
|
|
_lookup = lookup;
|
|
}
|
|
public override bool CanConvert(Type typeToConvert)
|
|
{
|
|
// Only convert actual domain types, not enums or primitives
|
|
return typeToConvert == typeof(T) &&
|
|
!typeToConvert.IsEnum &&
|
|
!typeToConvert.IsPrimitive &&
|
|
typeToConvert != typeof(string);
|
|
}
|
|
|
|
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
{
|
|
// Parse the incoming JSON into a GeneralIdRef
|
|
using var doc = JsonDocument.ParseValue(ref reader);
|
|
var json = doc.RootElement.GetRawText();
|
|
|
|
var idRef = JsonSerializer.Deserialize<GeneralIdRef>(json, options);
|
|
|
|
if (idRef == null)
|
|
return default;
|
|
|
|
return _lookup(idRef);
|
|
}
|
|
|
|
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
|
|
{
|
|
throw new NotImplementedException("Writing not needed.");
|
|
}
|
|
} |