| title | StorageMap & Serialisation | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| actions |
|
||||||||
| material |
|
Now that we are familiar with storing simple values, our goal now is to store all the Alien objects that we have created. Since the contract will create many aliens, we will need:
- A data structure that can contain a large collection of key-value pairs, and differentiate between each alien.
- A way to serialise objects into byte[] type that can be saved into storage
A Map data structure is a collection of key-value pairs, where each element has a unique key. StorageMap is a type provided by Neo framework to read and write data in a Map structure. It can be initialised like this:
StorageMap someMap = Storage.CurrentContext.CreateMap (nameof (someMap));Note that the CreateMap () constructor is a member of the StorageContext class.
It has similar methods to the Storage class:
someMap.Get (key): returns the byte[] corresponding to the keysomeMap.Put (key, value): Puts value into the corresponding key.someMap.Delete (key)
The same as Storage, StorageMap methods accept string and byte[] as keys, and string, byte[] and BigInteger as values.
For saving Aliens we have created, we can construct a dedicated map, use each Alien's Id property as keys.
Note that BigInteger type has built-in ToByteArray method.
Neo provides an auxiliary class to help with conversion from objects to and from byte[]. They can be intialised at the start of a contract like this:
using Helper = Neo.SmartContract.Framework.Helper;Here is an example of serialising and deserialisng objects with Helper:
// Serialise
byte[] value = Helper.Serialize (myCar);
// Deserialise
Car obj = Helper.Deserialize (value) as Car; // Explicitly casts the deserialised object as type Car- Initiate Helper at the start of the file.
- In
GenerateAlien (), Create aStorageMaptype calledalienMap - Deserialise the newly created
Alien, convert this Alien'sIdtobyte[], save the data withIdas the key, andAlienas the value. (try to do it in one line)