Fixing JSON

This commit is contained in:
dingo
2025-11-04 15:09:56 -05:00
parent 5b66567726
commit 6c4ba9b568
2 changed files with 74 additions and 12 deletions
@@ -0,0 +1,53 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Server.Networking.Messages
{
/// <summary>
/// Accepts either:
/// - base64 string (standard STJ behavior), or
/// - JSON array of numbers (0..255), e.g. [1,2,3]
/// </summary>
public sealed class FlexibleByteArrayConverter : JsonConverter<byte[]>
{
public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
// Standard path: base64 string
return reader.GetBytesFromBase64();
}
if (reader.TokenType == JsonTokenType.StartArray)
{
var bytes = new List<byte>(64);
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndArray)
break;
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException("Payload array must contain only numbers.");
if (!reader.TryGetInt32(out int value) || value < 0 || value > 255)
throw new JsonException("Payload numbers must be 0..255.");
bytes.Add((byte)value);
}
return bytes.ToArray();
}
throw new JsonException($"Unsupported token for byte[]: {reader.TokenType}");
}
public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
{
// Standard STJ behavior: write as base64 string
writer.WriteBase64StringValue(value);
}
}
}