2023-11-21 20:37:50 +00:00
|
|
|
// Copyright (c) 2023 Timothy Schenk. Subject to the GNU AGPL Version 3 License.
|
2023-11-20 18:58:30 +00:00
|
|
|
|
2023-11-08 18:04:37 +00:00
|
|
|
using System.Text.Json;
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
|
|
|
namespace Wonderking.Utils;
|
|
|
|
|
|
|
|
public class ByteArrayConverter : JsonConverter<byte[]>
|
|
|
|
{
|
|
|
|
public override byte[] Read(
|
|
|
|
ref Utf8JsonReader reader,
|
|
|
|
Type typeToConvert,
|
|
|
|
JsonSerializerOptions options)
|
|
|
|
{
|
|
|
|
var hexData = reader.GetString();
|
|
|
|
if (hexData != null)
|
|
|
|
{
|
|
|
|
return hexData.Split('-').Select(b => Convert.ToByte(b, 16)).ToArray();
|
|
|
|
}
|
2023-11-19 16:07:28 +00:00
|
|
|
|
2023-11-08 18:04:37 +00:00
|
|
|
throw new JsonException("Hex string is null.");
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void Write(
|
|
|
|
Utf8JsonWriter writer,
|
|
|
|
byte[]? value,
|
|
|
|
JsonSerializerOptions options)
|
|
|
|
{
|
|
|
|
if (value == null)
|
|
|
|
{
|
|
|
|
writer.WriteNullValue();
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
var hexData = BitConverter.ToString(value).Replace("-", string.Empty);
|
|
|
|
writer.WriteStringValue(hexData);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|