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);
}
}
}
+21 -12
View File
@@ -1,20 +1,29 @@
using System;
using System.Text.Json;
namespace Server.Networking.Messages;
public sealed class JsonSerializerAdapter : IMessageSerializer
namespace Server.Networking.Messages
{
private static readonly JsonSerializerOptions Options = new()
public sealed class JsonSerializerAdapter : IMessageSerializer
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false,
IncludeFields = true
};
private static readonly JsonSerializerOptions Options = CreateOptions();
public byte[] Serialize<T>(T message) =>
JsonSerializer.SerializeToUtf8Bytes(message, Options);
private static JsonSerializerOptions CreateOptions()
{
var o = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true, // accept opCode / OpCode
WriteIndented = false,
IncludeFields = true
};
o.Converters.Add(new FlexibleByteArrayConverter());
return o;
}
public T Deserialize<T>(ReadOnlyMemory<byte> bytes) =>
JsonSerializer.Deserialize<T>(bytes.Span, Options)!;
public byte[] Serialize<T>(T message) =>
JsonSerializer.SerializeToUtf8Bytes(message, Options);
public T Deserialize<T>(ReadOnlyMemory<byte> bytes) =>
JsonSerializer.Deserialize<T>(bytes.Span, Options)!;
}
}