Больше обработчиков
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Pf2eModel;
|
||||
using Pf2eModel.Model;
|
||||
using Pf2eModel.Model.Base;
|
||||
using Pf2eModel.Model.Structure;
|
||||
|
||||
namespace Pf2eViewer;
|
||||
internal class EntityConverter : JsonConverter
|
||||
{
|
||||
private readonly Pf2eDbContext _context = new();
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof(Entity) || objectType.IsAssignableTo(typeof(IEntity));
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||
{
|
||||
JToken token = JToken.FromObject(value!);
|
||||
|
||||
if (token.Type != JTokenType.Object)
|
||||
{
|
||||
token.WriteTo(writer);
|
||||
return;
|
||||
}
|
||||
|
||||
JObject obj = (JObject) token;
|
||||
|
||||
switch (value)
|
||||
{
|
||||
case Entity e:
|
||||
obj = ProcessEntity(obj, e);
|
||||
break;
|
||||
}
|
||||
|
||||
obj.WriteTo(writer);
|
||||
}
|
||||
|
||||
private JObject ProcessEntity(JObject obj, Entity e)
|
||||
{
|
||||
List<int> traitIds = e.Traits.Select(t => t.Id).ToList();
|
||||
List<Trait> traits = _context.Traits.Where(t => traitIds.Contains(t.Id)).Include(t => t.Entity).ToList();
|
||||
|
||||
foreach (JToken item in (JArray) obj.SelectToken("Traits")!)
|
||||
{
|
||||
JObject o = (JObject) item;
|
||||
int id = o.SelectToken("Id")!.ToObject<int>();
|
||||
|
||||
o.Add("Name", traits.FirstOrDefault(t => t.Id == id)!.Entity.Name);
|
||||
}
|
||||
|
||||
obj.Remove("Description");
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||
{
|
||||
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user