diff --git a/Projects/Server/JsonConfiguration/Converters/NullableStructSerializer.cs b/Projects/Server/JsonConfiguration/Converters/NullableStructSerializer.cs new file mode 100644 index 000000000..622c1e3d2 --- /dev/null +++ b/Projects/Server/JsonConfiguration/Converters/NullableStructSerializer.cs @@ -0,0 +1,18 @@ +namespace System.Text.Json.Serialization +{ + public class NullableStructSerializer : JsonConverter where TStruct : struct + { + public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => + reader.TokenType == JsonTokenType.Null + ? default + : JsonSerializer.Deserialize(ref reader, options); + + public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options) + { + if (value == null) + writer.WriteNullValue(); + else + JsonSerializer.Serialize(writer, value.Value, options); + } + } +} diff --git a/Projects/Server/JsonConfiguration/Converters/NullableStructSerializerFactory.cs b/Projects/Server/JsonConfiguration/Converters/NullableStructSerializerFactory.cs new file mode 100644 index 000000000..01b4b056e --- /dev/null +++ b/Projects/Server/JsonConfiguration/Converters/NullableStructSerializerFactory.cs @@ -0,0 +1,19 @@ +namespace System.Text.Json.Serialization +{ + public class NullableStructSerializerFactory : JsonConverterFactory + { + public override bool CanConvert(Type typeToConvert) + { + if (!typeToConvert.IsGenericType || typeToConvert.GetGenericTypeDefinition() != typeof(Nullable<>)) + return false; + + var structType = typeToConvert.GenericTypeArguments[0]; + return !structType.IsPrimitive && structType.Namespace?.StartsWith(nameof(System)) != true && !structType.IsEnum; + } + + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => + (JsonConverter)Activator.CreateInstance( + typeof(NullableStructSerializer<>).MakeGenericType(typeToConvert.GenericTypeArguments[0]) + ); + } +} diff --git a/Projects/Server/JsonConfiguration/JsonConfig.cs b/Projects/Server/JsonConfiguration/JsonConfig.cs index db63ecb9b..caa048008 100644 --- a/Projects/Server/JsonConfiguration/JsonConfig.cs +++ b/Projects/Server/JsonConfiguration/JsonConfig.cs @@ -46,6 +46,7 @@ namespace Server.Json options.Converters.Add(new Rectangle3DConverterFactory()); options.Converters.Add(new TimeSpanConverterFactory()); options.Converters.Add(new IPEndPointConverterFactory()); + options.Converters.Add(new NullableStructSerializerFactory()); for (var i = 0; i < converters.Length; i++) options.Converters.Add(converters[i]);