using System.Text.Json; using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol; /// /// Serializes a as the wire's numeric 0/1. The client reads these flags via /// Convert.ToInt32 / Convert.ToBoolean (e.g. isOfficial, isInvoke) — /// never as a JSON true/false token — so a real bool property must still emit /// a number. Read accepts a JSON number (0 = false, non-zero = true) and, defensively, a /// true/false token or a numeric string. Applied per-field via /// [JsonConverter(typeof(NumericBoolJsonConverter))]; works on bool? too (System.Text.Json /// wraps a JsonConverter<bool> for the nullable case). /// public sealed class NumericBoolJsonConverter : JsonConverter { public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType switch { JsonTokenType.Number => reader.GetInt64() != 0, JsonTokenType.True => true, JsonTokenType.False => false, JsonTokenType.String => long.TryParse(reader.GetString(), out var n) && n != 0, _ => throw new JsonException($"Cannot convert token {reader.TokenType} to a numeric bool"), }; public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) => writer.WriteNumberValue(value ? 1 : 0); }