2025-06-23 12:14:35 +00:00
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
|
|
|
|
|
namespace AIStudio.Settings.DataModel;
|
|
|
|
|
|
|
|
|
|
public class MetadataJsonConverter : JsonConverter<Metadata>
|
|
|
|
|
{
|
2025-06-24 08:16:39 +00:00
|
|
|
|
private static readonly Dictionary<string, Type> TYPE_MAP = new()
|
|
|
|
|
{
|
|
|
|
|
{ "Text", typeof(TextMetadata) },
|
|
|
|
|
{ "Pdf", typeof(PdfMetadata) },
|
|
|
|
|
{ "Spreadsheet", typeof(SpreadsheetMetadata) },
|
|
|
|
|
{ "Presentation", typeof(PresentationMetadata) },
|
|
|
|
|
{ "Image", typeof(ImageMetadata) },
|
|
|
|
|
{ "Document", typeof(DocumentMetadata) }
|
|
|
|
|
};
|
|
|
|
|
|
2025-06-23 12:14:35 +00:00
|
|
|
|
public override Metadata? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
|
|
|
{
|
2025-06-24 08:16:39 +00:00
|
|
|
|
using var jsonDoc = JsonDocument.ParseValue(ref reader);
|
|
|
|
|
var root = jsonDoc.RootElement;
|
|
|
|
|
var rawText = root.GetRawText();
|
2025-06-23 12:14:35 +00:00
|
|
|
|
|
2025-06-24 08:16:39 +00:00
|
|
|
|
var propertyName = root.EnumerateObject()
|
|
|
|
|
.Select(p => p.Name)
|
|
|
|
|
.FirstOrDefault(name => TYPE_MAP.ContainsKey(name));
|
|
|
|
|
|
|
|
|
|
if (propertyName != null && TYPE_MAP.TryGetValue(propertyName, out var metadataType))
|
2025-06-23 12:14:35 +00:00
|
|
|
|
{
|
2025-06-24 08:16:39 +00:00
|
|
|
|
return (Metadata?)JsonSerializer.Deserialize(rawText, metadataType, options);
|
2025-06-23 12:14:35 +00:00
|
|
|
|
}
|
2025-06-24 08:16:39 +00:00
|
|
|
|
|
|
|
|
|
return null;
|
2025-06-23 12:14:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2025-06-24 08:16:39 +00:00
|
|
|
|
public override void Write(Utf8JsonWriter writer, Metadata value, JsonSerializerOptions options) => JsonSerializer.Serialize(writer, value, value.GetType(), options);
|
2025-06-23 12:14:35 +00:00
|
|
|
|
}
|