Jacob Stein
Jacob Stein

Reputation: 322

Converting an object back into a class using Json.NET

Hello people of Stack Overflow! I'm currently working with a framework for Unity called Oxide, which is irrelevant. However, the configuration helper only allows me to serialize lists of objects, which isn't great since I'm trying to serialize a custom class. I'm not sure if this is a limitation of Json.NET or the framework itself. Basically, I am loading a list of my custom class, ShopItem, as objects, then serializing/reading it on load (micro-kernel architecture). I'd like to convert the objects back to my class after, though they're always null. I have tried making a custom JsonConverter, which failed. This is the terrible hack I'm currently using.

foreach (var shopItem in Instance.Configuration.ItemsToSellToPlayers.Select(x =>
(ShopItem)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x), typeof(ShopItem))))

Here's the ShopItem class:

public class ShopItem
{
    public int Amount;
    public double Price;
    public string ShortName;
    public ulong SkinId;

    public ShopItem()
    {
    }

    public ShopItem(int amount, double price, string shortName, ulong skinId = 0)
    {
        Amount = amount;
        Price = price;
        ShortName = shortName;
        SkinId = skinId;
     }

     public Item Create()
     {
        var item = ItemManager.CreateByName(ShortName, Amount, SkinId);
        item.name = $"{item.info.displayName.english} - ${Price}";
        return item;
     }
}

Does anyone have a suggestion as to how I should convert

ItemsToBuyFromPlayers = new List<object>
{
    new ShopItem(1, 1, "stones"),
    new ShopItem(1, 1, "wood")
};

back to an instance my class?

NOTE: Typical casting ((ShopItem)x) doesn't work.

Upvotes: 0

Views: 348

Answers (1)

pkuderov
pkuderov

Reputation: 3571

The problem is here:

// you create the List of `object`s
ItemsToBuyFromPlayers = new List<object>
{
    new ShopItem(1, 1, "stones"),
    new ShopItem(1, 1, "wood")
};

The right way:

var shopItems = new List<ShopItem>
{
    new ShopItem(1, 1, "stones"),
    new ShopItem(1, 1, "wood")
};

var serialized = JsonConvert.SerializeObject(shopItems);
var copyOfShopItems = JsonConvert.DeserializeObject<List<ShopItem>>(serialized);

Upvotes: 1

Related Questions