mcdiscordbot/MinecraftDiscordBot/Models/ModItemId.cs

31 lines
1.3 KiB
C#
Raw Normal View History

using Newtonsoft.Json;
using System.Diagnostics;
namespace MinecraftDiscordBot.Models;
[JsonConverter(typeof(ModItemIdJsonConverter))]
[DebuggerDisplay($"{{{nameof(ToString)}(),nq}}")]
public class ModItemId {
public ModItemId(string name) {
var colon = name.IndexOf(':');
if (colon < 0) throw new ArgumentException("Invalid mod item id!", nameof(name));
ModName = name[..colon];
ModItem = name[(colon + 1)..];
if (ToString() != name) throw new InvalidProgramException("Bad Parsing!");
}
public override string ToString() => $"{ModName}:{ModItem}";
public string ModName { get; }
public string ModItem { get; }
public class ModItemIdJsonConverter : JsonConverter<ModItemId> {
public override ModItemId? ReadJson(JsonReader reader, Type objectType, ModItemId? existingValue, bool hasExistingValue, JsonSerializer serializer)
=> reader.Value is string value
? new(value)
: throw new JsonException($"Could not parse mod name with token '{reader.Value}'");
public override void WriteJson(JsonWriter writer, ModItemId? value, JsonSerializer serializer) {
if (value is null) writer.WriteNull();
else writer.WriteValue(value.ToString());
}
}
}