diff --git a/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/AbstractModMetadata.cs b/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/AbstractModMetadata.cs index 17d0c4353..b711730e5 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/AbstractModMetadata.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/AbstractModMetadata.cs @@ -1,4 +1,6 @@ -using Range = SemanticVersioning.Range; +using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Utils.Json.Converters; +using Range = SemanticVersioning.Range; using Version = SemanticVersioning.Version; namespace SPTarkov.Server.Core.Models.Spt.Mod; @@ -40,6 +42,7 @@ public abstract record AbstractModMetadata ///
/// Version = new Version("1.0.0.0"); is not /// + [JsonConverter(typeof(ToStringJsonConverter))] public abstract Version Version { get; init; } /// @@ -49,6 +52,7 @@ public abstract record AbstractModMetadata ///
/// Version = new Version("4.0.0.0"); is not ///
+ [JsonConverter(typeof(ToStringJsonConverter))] public abstract Range SptVersion { get; init; } /// diff --git a/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/ToStringJsonConverter.cs b/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/ToStringJsonConverter.cs new file mode 100644 index 000000000..11069f084 --- /dev/null +++ b/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/ToStringJsonConverter.cs @@ -0,0 +1,42 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace SPTarkov.Server.Core.Utils.Json.Converters; + +internal class ToStringJsonConverter : JsonConverter +{ + public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return default; + } + + if (reader.TokenType == JsonTokenType.String) + { + var value = reader.GetString(); + try + { + return (T?)Activator.CreateInstance(typeToConvert, value); + } + catch (Exception ex) + { + throw new JsonException($"Unable to convert \"{value}\" to {typeof(T).Name}.", ex); + } + } + + throw new JsonException($"Expected string to deserialize {typeof(T).Name} but got {reader.TokenType}."); + } + + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + if (value == null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value.ToString()); + } + } +}