using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public string cardName = "Card";
public string description = "Description";
public bool isStackable = false;
public ItemType itemType = ItemType.Item;
public class CardConverter : JsonConverter
private static readonly Dictionary<string, Func<Card>> cardFactory = new Dictionary<string, Func<Card>>
{ "Health Potion", () => new HealthPotion() },
{ "Stone", () => new Stone() },
{ "Iron Helmet", () => new IronHelmet() },
{ "Iron Chestpiece", () => new IronChestpiece() },
{ "Iron Boots", () => new IronBoots() },
{ "Iron Shield", () => new IronShield() },
{ "Iron Sword", () => new IronSword() },
{ "Shield", () => new Shield() },
{ "Reinforced Shield", () => new IronShield() },
{ "Bow", () => new Bow() },
{ "Arrow", () => new Arrow() },
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
JObject obj = new JObject
{ "cardName", card.cardName },
{ "description", card.description },
{ "rarity", card.rarity },
{ "isStackable", card.isStackable },
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
JObject obj = JObject.Load(reader);
string cardName = obj["cardName"]?.ToString();
if (string.IsNullOrEmpty(cardName))
Card card = CreateCardFromCardName(cardName);
card.cardName = cardName;
card.description = obj["description"]?.ToString();
card.uses = obj["uses"]?.ToObject<int>() ?? 0;
card.rarity = obj["rarity"]?.ToObject<int>() ?? 0;
card.isStackable = obj["isStackable"]?.ToObject<bool>() ?? false;
card.count = obj["count"]?.ToObject<int>() ?? 1;
public override bool CanConvert(Type objectType)
return typeof(Card).IsAssignableFrom(objectType);
private Card CreateCardFromCardName(string cardName)
if (cardFactory.TryGetValue(cardName, out var createCard))
public static void Test()
Card testCard = new Card();
string json = JsonConvert.SerializeObject(testCard, Formatting.Indented, new JsonSerializerSettings
Converters = new List<JsonConverter> { new CardConverter() }
Console.WriteLine($"Serialized JSON: {json}");
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");