ExtensionsDictionaryClass.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public static class ExtensionsDictionaryClass
  5. {
  6. public static string ToJson<TKey, TValue>(this Dictionary<TKey, TValue> source)
  7. {
  8. return JsonUtility.ToJson(new ExtensionsDictionaryClass.SerializeDictionary<TKey, TValue>(source));
  9. }
  10. public static string ToJson<TKey, TValue>(this Dictionary<TKey, TValue> source, bool prettyPrint)
  11. {
  12. return JsonUtility.ToJson(new ExtensionsDictionaryClass.SerializeDictionary<TKey, TValue>(source), prettyPrint);
  13. }
  14. public static void FromJson<TKey, TValue>(this Dictionary<TKey, TValue> source, string jsonText)
  15. {
  16. ExtensionsDictionaryClass.SerializeDictionary<TKey, TValue> serializeDictionary = JsonUtility.FromJson<ExtensionsDictionaryClass.SerializeDictionary<TKey, TValue>>(jsonText);
  17. source.Clear();
  18. if (serializeDictionary.keys != null)
  19. {
  20. for (int i = 0; i < serializeDictionary.keys.Length; i++)
  21. {
  22. source.Add(serializeDictionary.keys[i], serializeDictionary.values[i]);
  23. }
  24. }
  25. }
  26. [Serializable]
  27. public class SerializeDictionary<Tkey, TVal>
  28. {
  29. public SerializeDictionary(Dictionary<Tkey, TVal> src)
  30. {
  31. if (src == null)
  32. {
  33. this.keys = new Tkey[0];
  34. this.values = new TVal[0];
  35. return;
  36. }
  37. this.keys = new Tkey[src.Count];
  38. this.values = new TVal[src.Count];
  39. int num = 0;
  40. foreach (KeyValuePair<Tkey, TVal> keyValuePair in src)
  41. {
  42. this.keys[num] = keyValuePair.Key;
  43. this.values[num] = keyValuePair.Value;
  44. num++;
  45. }
  46. }
  47. public Tkey[] keys;
  48. public TVal[] values;
  49. }
  50. }