Creating a custom json serializer for PeopleRoles

This commit is contained in:
Zoe Roux 2021-03-08 23:53:46 +01:00
parent b3fdee4bcd
commit d3d2677a83
4 changed files with 27 additions and 5 deletions

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Kyoo.Models.Attributes;
namespace Kyoo.Models
@ -12,7 +9,6 @@ namespace Kyoo.Models
[SerializeIgnore] public string Slug => ForPeople ? Show.Slug : People.Slug;
[SerializeIgnore] public bool ForPeople;
[SerializeIgnore] public int PeopleID { get; set; }
// TODO implement a SerializeInline for People or Show depending on the context.
[SerializeIgnore] public virtual People People { get; set; }
[SerializeIgnore] public int ShowID { get; set; }
[SerializeIgnore] public virtual Show Show { get; set; }

View File

@ -4,6 +4,7 @@ using System.Reflection;
using Kyoo.Models;
using Kyoo.Models.Attributes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Kyoo.Controllers
@ -52,4 +53,24 @@ namespace Kyoo.Controllers
return contract;
}
}
public class PeopleRoleConverter : JsonConverter<PeopleRole>
{
public override void WriteJson(JsonWriter writer, PeopleRole value, JsonSerializer serializer)
{
// TODO this seems to not use the property.ShouldSerialize and cause an recursive inclusion error.
JToken t = JToken.FromObject(value, serializer);
JObject obj = t as JObject;
writer.WriteValue(obj);
}
public override PeopleRole ReadJson(JsonReader reader,
Type objectType,
PeopleRole existingValue,
bool hasExistingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}

View File

@ -43,7 +43,11 @@ namespace Kyoo
});
services.AddControllers()
.AddNewtonsoftJson(x => x.SerializerSettings.ContractResolver = new JsonPropertyIgnorer());
.AddNewtonsoftJson(x =>
{
x.SerializerSettings.ContractResolver = new JsonPropertyIgnorer();
x.SerializerSettings.Converters.Add(new PeopleRoleConverter());
});
services.AddHttpClient();
services.AddDbContext<DatabaseContext>(options =>

View File

@ -15,6 +15,7 @@ namespace Kyoo.Api
[Route("api/item")]
[Route("api/items")]
[ApiController]
[ResourceView]
public class LibraryItemApi : ControllerBase
{
private readonly ILibraryItemRepository _libraryItems;