wabbajack/Wabbajack.DTOs/JsonConverters/DTOSerializer.cs

54 lines
1.5 KiB
C#
Raw Permalink Normal View History

2021-09-27 12:42:46 +00:00
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.DTOs.JsonConverters;
public class DTOSerializer
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
public readonly JsonSerializerOptions Options;
public DTOSerializer(IEnumerable<JsonConverter> converters)
{
Options = new JsonSerializerOptions();
Options.NumberHandling = JsonNumberHandling.AllowReadingFromString;
foreach (var c in converters) Options.Converters.Add(c);
}
public T? Deserialize<T>(string text)
{
return JsonSerializer.Deserialize<T>(text, Options);
}
public ValueTask<T?> DeserializeAsync<T>(Stream stream, CancellationToken? token = null)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
return JsonSerializer.DeserializeAsync<T>(stream, Options, token ?? CancellationToken.None);
}
public string Serialize<T>(T data, bool writeIndented = false)
{
var options = Options;
if (writeIndented)
options = new JsonSerializerOptions(Options)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
WriteIndented = true
};
return JsonSerializer.Serialize(data, options);
}
public async Task Serialize<T>(T data, Stream of, bool writeIndented = false)
{
var options = Options;
if (writeIndented)
options = new JsonSerializerOptions(Options)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
WriteIndented = true
};
await JsonSerializer.SerializeAsync(of, data, options);
2021-09-27 12:42:46 +00:00
}
}