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 { /// /// Accepts either: /// - base64 string (standard STJ behavior), or /// - JSON array of numbers (0..255), e.g. [1,2,3] /// public sealed class FlexibleByteArrayConverter : JsonConverter { 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(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); } } }