JsonHelper.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #if !COMBAT_SERVER
  2. using System;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace Fort23.GameData
  6. {
  7. public class JsonHelper
  8. {
  9. public static string ToJson(object obj)
  10. {
  11. #if !COMBAT_SERVER
  12. return JsonUtility.ToJson(obj);
  13. #endif
  14. return null;
  15. }
  16. public static T FromJson<T>(string json)
  17. {
  18. #if !COMBAT_SERVER
  19. return JsonUtility.FromJson<T>(json);
  20. #endif
  21. return default;
  22. }
  23. public static object FromJson(string json, Type type)
  24. {
  25. #if !COMBAT_SERVER
  26. return JsonUtility.FromJson(json, type);
  27. #endif
  28. return null;
  29. }
  30. public static T Clone<T>(T t)
  31. {
  32. return FromJson<T>(ToJson(t));
  33. }
  34. }
  35. /// <summary>
  36. /// 扩展JsonUtility的List能力, T必须加上[Serializable]标签
  37. /// https://blog.csdn.net/Truck_Truck/article/details/78292390
  38. /// </summary>
  39. /// <typeparam name="T"></typeparam>
  40. [Serializable]
  41. public class Serialization<T>
  42. {
  43. [SerializeField] List<T> target;
  44. public List<T> ToList()
  45. {
  46. return target;
  47. }
  48. public Serialization(List<T> target)
  49. {
  50. this.target = target;
  51. }
  52. }
  53. /// <summary>
  54. /// 扩展JsonUtility的Dictionary能力,TValue必须加上[Serializable]标签
  55. /// Dictionary<TKey, TValue>
  56. /// </summary>
  57. /// <typeparam name="TKey"></typeparam>
  58. /// <typeparam name="TValue"></typeparam>
  59. [Serializable]
  60. public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
  61. {
  62. [SerializeField] List<TKey> keys;
  63. [SerializeField] List<TValue> values;
  64. Dictionary<TKey, TValue> target;
  65. public Dictionary<TKey, TValue> ToDictionary()
  66. {
  67. return target;
  68. }
  69. public Serialization(Dictionary<TKey, TValue> target)
  70. {
  71. this.target = target;
  72. }
  73. public void OnBeforeSerialize()
  74. {
  75. keys = new List<TKey>(target.Keys);
  76. values = new List<TValue>(target.Values);
  77. }
  78. public void OnAfterDeserialize()
  79. {
  80. var count = Math.Min(keys.Count, values.Count);
  81. target = new Dictionary<TKey, TValue>(count);
  82. for (var i = 0; i < count; ++i)
  83. {
  84. target.Add(keys[i], values[i]);
  85. }
  86. }
  87. }
  88. }
  89. #endif