Search Unity

Showcase Dictionary Data Class for JSON Serialization

Discussion in 'Scripting' started by Shugabush, Oct 16, 2022.

  1. Shugabush

    Shugabush

    Joined:
    Nov 6, 2021
    Posts:
    13
    Below is some code that I wrote for dictionary saving with unity. It basically takes a key and value type and stores them in lists, although you'll need to call SaveToLists() and LoadFromLists() if you want the data from the dictionary to be serialized to json. I've also included a bunch of functions and properties. You can implicitly convert a dictionary data to a dictionary and vice versa. So basically you can use this as if it were a dictionary, except that it also contains the key and value lists for saving to JSON. I hope this is helpful to people who are using JSON to save their game data.


    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using UnityEngine;

    /// <summary>
    /// Data that stores a dictionary and two lists containing the keys and values
    /// Those lists are what will be saved to json as dictionaries can't be serialized to json
    /// </summary>
    /// <typeparam name="TKey">The key type</typeparam>
    /// <typeparam name="TValue">The value type</typeparam>
    [System.Serializable]
    public class DictionaryData<TKey, TValue>
    {
    [SerializeField] List<TKey> keys = new List<TKey>();
    [SerializeField] List<TValue> values = new List<TValue>();

    [SerializeField] Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

    public TValue this[TKey index]
    {
    get
    {
    return dictionary[index];
    }
    }

    // With these, we can pass an instance of this class in directly as a dictionary and vice versa
    public static implicit operator Dictionary<TKey, TValue>(DictionaryData<TKey, TValue> dictionaryData)
    {
    return dictionaryData.dictionary;
    }
    public static implicit operator DictionaryData<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
    {
    DictionaryData<TKey, TValue> newDictionary = new DictionaryData<TKey, TValue>();
    newDictionary.dictionary = dictionary;
    return newDictionary;
    }

    public IEqualityComparer<TKey> Comparer => dictionary.Comparer;
    public Dictionary<TKey, TValue>.KeyCollection Keys => dictionary.Keys;
    public Dictionary<TKey, TValue>.ValueCollection Values => dictionary.Values;
    public int Count => dictionary.Count;

    public void TrimExcess()
    {
    dictionary.TrimExcess();
    }
    public void TrimExcess(int capacity)
    {
    dictionary.TrimExcess(capacity);
    }
    public int EnsureCapacity(int capacity)
    {
    return dictionary.EnsureCapacity(capacity);
    }
    public Dictionary<TKey, TValue>.Enumerator GetEnumerator()
    {
    return dictionary.GetEnumerator();
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
    dictionary.GetObjectData(info, context);
    }
    public bool ContainsKey(TKey index)
    {
    return dictionary.ContainsKey(index);
    }
    public void Add(TKey key, TValue value)
    {
    dictionary.Add(key, value);
    }
    public bool TryAdd(TKey key, TValue value)
    {
    return dictionary.TryAdd(key, value);
    }
    public bool TryGetValue(TKey key, out TValue value)
    {
    return dictionary.TryGetValue(key, out value);
    }
    public bool Remove(TKey key)
    {
    return dictionary.Remove(key);
    }
    public bool Remove(TKey key, out TValue value)
    {
    return dictionary.Remove(key, out value);
    }
    public void Clear()
    {
    dictionary.Clear();
    }
    public void OnDeserialization(object sender)
    {
    dictionary.OnDeserialization(sender);
    }
    public TValue GetValueOrDefault(TKey key)
    {
    return dictionary.GetValueOrDefault(key);
    }
    public TValue GetValueOrDefault(TKey key, TValue defaultValue)
    {
    return dictionary.GetValueOrDefault(key, defaultValue);
    }
    public override string ToString()
    {
    return dictionary.ToString();
    }
    public override bool Equals(object obj)
    {
    return dictionary.Equals(obj);
    }
    public override int GetHashCode()
    {
    return dictionary.GetHashCode();
    }

    /// <summary>
    /// Call this when you want to
    /// save the dictionary's keys and values
    /// into the key and value lists
    /// </summary>
    public void SaveToLists()
    {
    keys = new List<TKey>(dictionary.Keys);
    values = new List<TValue>(dictionary.Values);
    }

    /// <summary>
    /// Call this when you want to
    /// load the keys and values
    /// into the dictionary
    /// </summary>
    public void LoadFromLists()
    {
    dictionary.Clear();
    for (int i = 0; i < keys.Count && i < values.Count; i++)
    {
    dictionary.Add(keys[i], values[i]);
    }
    }
    }