Custom JSON Deserializer for concrete classes of abstract class TrangaTask

This commit is contained in:
glax 2023-05-31 21:43:07 +02:00
parent d477cd1ccd
commit d9b6062767
2 changed files with 30 additions and 1 deletions

View File

@ -307,7 +307,7 @@ public class TaskManager
{
logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
buffer = File.ReadAllText(settings.tasksFilePath);
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer)!;
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
}
if (File.Exists(settings.knownPublicationsPath))

View File

@ -1,4 +1,6 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tranga.TrangaTasks;
namespace Tranga;
@ -56,4 +58,31 @@ public abstract class TrangaTask
{
return $"{task}, {lastExecuted}, {reoccurrence}, {state} {(connectorName is not null ? $", {connectorName}" : "" )} {(publication is not null ? $", {publication?.sortName}": "")}";
}
public class TrangaTaskJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(TrangaTask));
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadNewChapters)
return jo.ToObject<DownloadNewChaptersTask>(serializer)!;
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateKomgaLibrary)
return jo.ToObject<UpdateKomgaLibraryTask>(serializer)!;
throw new Exception();
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new Exception("Dont call this");
}
}
}