Files
harmonia/Harmonia.Core/Data/JsonFileRepository.cs

32 lines
984 B
C#

using System.Text.Json.Serialization;
using System.Text.Json;
namespace Harmonia.Core.Data;
public abstract class JsonFileRepository<TObject> : FileRepository<TObject> where TObject : notnull, new()
{
private readonly JsonSerializerOptions _options = new()
{
WriteIndented = true,
IgnoreReadOnlyProperties = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
protected override string Extension => "json";
protected override async Task<TObject> DeserializeAsync(Stream stream)
{
return await JsonSerializer.DeserializeAsync<TObject>(stream) ?? new();
}
protected override async Task<string> SerializeAsync(TObject obj)
{
using MemoryStream memoryStream = new();
await JsonSerializer.SerializeAsync(memoryStream, obj, _options);
memoryStream.Position = 0;
using StreamReader reader = new(memoryStream);
return await reader.ReadToEndAsync();
}
}