JsonFileSystem.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. using System.IO;
  2. using UnityEngine;
  3. using Newtonsoft.Json;
  4. namespace IntelligentProjectAnalyzer.Helper
  5. {
  6. /// <summary>
  7. /// A utility class for writing serializable objects to JSON files using Newtonsoft JSON.
  8. /// </summary>
  9. public static class JsonFileSystem
  10. {
  11. /// <summary>
  12. /// Writes a serializable object to a JSON file at a specified path.
  13. /// </summary>
  14. /// <typeparam name="T">The type of the data object to serialize.</typeparam>
  15. /// <param name="data">The object to serialize.</param>
  16. /// <param name="fullPath">The absolute path where the file will be saved.</param>
  17. /// <param name="prettyPrint">If true, the JSON will be formatted for human readability.</param>
  18. /// <param name="debugLogJson">If true, the generated JSON content will be logged to the console.</param>
  19. public static void Write<T>(T data, string fullPath, bool prettyPrint = false, bool debugLogJson = false)
  20. {
  21. if (data == null)
  22. {
  23. Debug.LogError("[JsonFileSystem] The data object provided is null. Cannot write file.");
  24. return;
  25. }
  26. if (string.IsNullOrEmpty(fullPath))
  27. {
  28. Debug.LogError("[JsonFileSystem] The full path provided is null or empty. Cannot write file.");
  29. return;
  30. }
  31. try
  32. {
  33. // Ensure the output directory exists.
  34. var outputDirectory = Path.GetDirectoryName(fullPath);
  35. if (!string.IsNullOrEmpty(outputDirectory) && !Directory.Exists(outputDirectory))
  36. {
  37. Directory.CreateDirectory(outputDirectory);
  38. }
  39. // Serialize the object to a JSON string using Newtonsoft JSON
  40. var json = GetJson(data, prettyPrint);
  41. // Optionally, log the JSON to the console for debugging.
  42. if (debugLogJson)
  43. {
  44. var fileName = Path.GetFileName(fullPath);
  45. Debug.Log($"[JsonFileSystem] JSON content for '{fileName}':\n{json}");
  46. }
  47. // Write the JSON string to the file.
  48. File.WriteAllText(fullPath, json);
  49. // Log a clickable link to the created file.
  50. Debug.Log($"[JsonFileSystem] Successfully wrote file to: <a href=\"{fullPath}\">{fullPath}</a>");
  51. }
  52. catch (System.Exception e)
  53. {
  54. // Catch any potential exceptions during file I/O or serialization.
  55. Debug.LogError($"[JsonFileSystem] An error occurred while writing file at '{fullPath}'.\nException: {e.Message}");
  56. }
  57. }
  58. public static string GetJson(object data, bool prettyPrint = false)
  59. {
  60. // Configure JSON serialization settings
  61. var settings = new JsonSerializerSettings
  62. {
  63. Formatting = prettyPrint ? Formatting.Indented : Formatting.None,
  64. NullValueHandling = NullValueHandling.Ignore,
  65. DefaultValueHandling = DefaultValueHandling.Include,
  66. TypeNameHandling = TypeNameHandling.Auto, // This handles derived classes
  67. ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  68. };
  69. var json = JsonConvert.SerializeObject(data, settings);
  70. return json;
  71. }
  72. /// <summary>
  73. /// Reads and deserializes a JSON file.
  74. /// </summary>
  75. /// <typeparam name="T">The type to deserialize to.</typeparam>
  76. /// <param name="fullPath">The absolute path to the JSON file.</param>
  77. /// <returns>The deserialized object, or default(T) if failed.</returns>
  78. public static T Read<T>(string fullPath)
  79. {
  80. if (string.IsNullOrEmpty(fullPath) || !File.Exists(fullPath))
  81. {
  82. Debug.LogError($"[JsonFileSystem] File not found: {fullPath}");
  83. return default;
  84. }
  85. try
  86. {
  87. var json = File.ReadAllText(fullPath);
  88. var settings = new JsonSerializerSettings
  89. {
  90. TypeNameHandling = TypeNameHandling.Auto,
  91. NullValueHandling = NullValueHandling.Ignore
  92. };
  93. return JsonConvert.DeserializeObject<T>(json, settings);
  94. }
  95. catch (System.Exception e)
  96. {
  97. Debug.LogError($"[JsonFileSystem] Error reading file '{fullPath}': {e.Message}");
  98. return default;
  99. }
  100. }
  101. public static object Read(string data, System.Type type)
  102. {
  103. if (string.IsNullOrEmpty(data))
  104. {
  105. Debug.LogError($"[JsonFileSystem] Data is null or empty");
  106. return null;
  107. }
  108. try
  109. {
  110. var settings = new JsonSerializerSettings
  111. {
  112. TypeNameHandling = TypeNameHandling.Auto,
  113. NullValueHandling = NullValueHandling.Ignore
  114. };
  115. return JsonConvert.DeserializeObject(data, type, settings);
  116. }
  117. catch (System.Exception e)
  118. {
  119. Debug.LogError($"[JsonFileSystem] Error reading passed data '{data}': {e.Message}");
  120. return null;
  121. }
  122. }
  123. }
  124. }