Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -40,6 +42,7 @@ public abstract record AbstractModMetadata
/// <br/>
/// Version = new Version("1.0.0.0"); is not
/// </summary>
[JsonConverter(typeof(ToStringJsonConverter<Version>))]
public abstract Version Version { get; init; }

/// <summary>
Expand All @@ -49,6 +52,7 @@ public abstract record AbstractModMetadata
/// <br/>
/// Version = new Version("4.0.0.0"); is not
/// </summary>
[JsonConverter(typeof(ToStringJsonConverter<Range>))]
public abstract Range SptVersion { get; init; }

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SPTarkov.Server.Core.Utils.Json.Converters;

internal class ToStringJsonConverter<T> : JsonConverter<T>
{
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());
}
}
}
Loading