continuity/Wonderking/Utils/ByteArrayConverter.cs
Timothy Schenk 3a24dabdf2
chore: formatting and slnx
Signed-off-by: Timothy Schenk <admin@rainote.dev>
2025-01-16 14:30:40 +01:00

33 lines
952 B
C#

// Licensed to Timothy Schenk under 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);
}
}
}