JsonSerializer.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using UnityEngine;
  5. using System.Reflection;
  6. #if UNITY_EDITOR
  7. using UnityEditor;
  8. #endif
  9. // Warning, the current serialization code does not handle unity objects
  10. // in play mode outside of the editor (because of JsonUtility)
  11. namespace GraphProcessor
  12. {
  13. [Serializable]
  14. public struct JsonElement
  15. {
  16. public string type;
  17. public string jsonDatas;
  18. public override string ToString()
  19. {
  20. return "type: " + type + " | JSON: " + jsonDatas;
  21. }
  22. }
  23. public static class JsonSerializer
  24. {
  25. public static JsonElement Serialize(object obj)
  26. {
  27. JsonElement elem = new JsonElement();
  28. elem.type = obj.GetType().AssemblyQualifiedName;
  29. #if UNITY_EDITOR
  30. elem.jsonDatas = EditorJsonUtility.ToJson(obj);
  31. #else
  32. elem.jsonDatas = JsonUtility.ToJson(obj);
  33. #endif
  34. return elem;
  35. }
  36. public static T Deserialize< T >(JsonElement e)
  37. {
  38. if (typeof(T) != Type.GetType(e.type))
  39. throw new ArgumentException("Deserializing type is not the same than Json element type");
  40. var obj = Activator.CreateInstance< T >();
  41. #if UNITY_EDITOR
  42. EditorJsonUtility.FromJsonOverwrite(e.jsonDatas, obj);
  43. #else
  44. JsonUtility.FromJsonOverwrite(e.jsonDatas, obj);
  45. #endif
  46. return obj;
  47. }
  48. public static JsonElement SerializeNode(BaseNode node)
  49. {
  50. return Serialize(node);
  51. }
  52. public static BaseNode DeserializeNode(JsonElement e)
  53. {
  54. try {
  55. var baseNodeType = Type.GetType(e.type);
  56. if (e.jsonDatas == null)
  57. return null;
  58. var node = Activator.CreateInstance(baseNodeType) as BaseNode;
  59. #if UNITY_EDITOR
  60. EditorJsonUtility.FromJsonOverwrite(e.jsonDatas, node);
  61. #else
  62. JsonUtility.FromJsonOverwrite(e.jsonDatas, node);
  63. #endif
  64. return node;
  65. } catch {
  66. return null;
  67. }
  68. }
  69. }
  70. }