#JSON Item database and deserialization

1 messages · Page 1 of 1 (latest)

sage frigate
gray ginkgo
#

However, how would you correctly deserialize items to their correct classes?
You don't, the deserializer does it for you, it doesn't look at the JSON to determine which object corresponds to which class, it does the inverse. It sees your class architecture and attempts to map the JSON to it, throwing exceptions if it can't

#

In addition, by deserializing the items, wouldn't they have to all be stored in memory?
Yes they would, but that would only be a few bytes per instance. It does not pose much issues on the usual gigabyte of RAM a simple game can take.

An alternative would be storing these items in ScriptableObjects instead, they live in your project files, and can be referenced from your scripts.

sage frigate
#

Ah I see. My current understanding of JSON deserialization using unity is through JSONUtility so please correct me if i'm wrong.

If I had a single JSON array with a variety of items, would the deserializer be able to map varying properties to their respective classes?

My current thinking is to have a large JSON array that stores all the items in the game. My current understanding is that JSONUtility cannot deserialize complex JSONs properly unless wrapped, so I would require a root class with a list of item class as one of the properties. Since the weapon class and potion class would be subclasses of the item superclass, this list would be able to store items generically.

My confusion arises from how I would structure a class architecture that would be able to properly map values to classes.

As a concrete example, if I had a sword item with the properties: (name, damage, durability), a health potion item with the properties: (name, healthRestored, stackCount) in a JSON array and weapon and potion classes that can use the respective values, how would I go about deserializing these items?

gray ginkgo
#

That's the main issue with the built-in JsonUtility, its limitations. Namely it doesn't handle top-level collections at all, and you have to make a wrapper class that holds the collection, as you said.

For your example:

abstract class Item {
  public string Name { get; set; }
}

class Sword : Item {
  public float Damage { get; set; }
  public float Durability { get; set; }
}

class HealthPotion : Item {
  public float HealthRestored { get; set; }
  public float StackCount { get; set; }
}

Repository:

class ItemRepo {
  public List<Item> Items { get; } = new List<Item>();
}

(de)serialization:

string json = JsonUtility.Serialize(someItemRepo);
ItemRepo repo = JsonUtility.Deserialize<ItemRepo>(json);
#

But if your items just hold data like you showed above, and that you're not planning on adding new items at runtime (ie. in a built game), just drop the serialization part and use ScriptableObjects, they would also work with the class structure I showed above.