39 lines
997 B
C#
39 lines
997 B
C#
// Copyright (c) 2023 Timothy Schenk. Subject to the GNU AGPL Version 3 License.
|
|
|
|
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();
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|