continuity/Wonderking/Utils/ByteArrayConverter.cs

34 lines
952 B
C#
Raw Permalink Normal View History

2024-02-07 15:40:36 +00:00
// Licensed to Timothy Schenk under the GNU AGPL Version 3 License.
2023-11-20 18:58:30 +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
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);
}
}
}