Binder.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO.Abstractions;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization;
  8. namespace Quadarax.Foundation.Core.Json
  9. {
  10. public class Binder
  11. {
  12. private IFileSystem _fileSystem;
  13. public JsonSerializerOptions SerializerOptions {get;private set;}
  14. public Binder(JsonSerializerOptions options): this(new FileSystem(), options)
  15. {
  16. }
  17. public Binder(IFileSystem fileSystemAbstraction, JsonSerializerOptions options)
  18. {
  19. _fileSystem = fileSystemAbstraction ?? throw new ArgumentNullException(nameof(fileSystemAbstraction));
  20. SerializerOptions = options;
  21. }
  22. public Binder(IFileSystem fileSystemAbstraction, bool isPrettyPrint = true, bool isIgnoringNullValues = true, int maxDepth = 100)
  23. {
  24. _fileSystem = fileSystemAbstraction ?? throw new ArgumentNullException(nameof(fileSystemAbstraction));
  25. var jsonOpt = new JsonSerializerOptions
  26. {
  27. IgnoreNullValues = isIgnoringNullValues,
  28. WriteIndented = isPrettyPrint,
  29. PropertyNameCaseInsensitive = true,
  30. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  31. MaxDepth = maxDepth
  32. };
  33. jsonOpt.Converters.Add(new JsonStringEnumConverter());
  34. SerializerOptions = jsonOpt;
  35. }
  36. public TObject? Load<TObject>(string fileName)
  37. {
  38. return (TObject?) Load(fileName, typeof(TObject));
  39. }
  40. public object? Load(string fileName, Type targetType)
  41. {
  42. if (targetType == null)
  43. throw new ArgumentNullException(nameof(targetType));
  44. if (string.IsNullOrEmpty(fileName))
  45. throw new ArgumentNullException(nameof(fileName));
  46. using (var reader = _fileSystem.File.OpenText(fileName))
  47. {
  48. var result = JsonSerializer.Deserialize(reader.ReadToEnd(),targetType, SerializerOptions);
  49. return result;
  50. }
  51. }
  52. public object? LoadFromString(string jsonString, Type targetType)
  53. {
  54. if (targetType == null)
  55. throw new ArgumentNullException(nameof(targetType));
  56. if (string.IsNullOrEmpty(jsonString))
  57. throw new ArgumentNullException(nameof(jsonString));
  58. var result = JsonSerializer.Deserialize(jsonString,targetType, SerializerOptions);
  59. return result;
  60. }
  61. public void LoadTo(string fileName, object target, Type targetType)
  62. {
  63. if (targetType == null)
  64. throw new ArgumentNullException(nameof(targetType));
  65. if (target == null)
  66. throw new ArgumentNullException(nameof(target));
  67. var shadow = Load(fileName, targetType);
  68. if (shadow == null) throw new InvalidOperationException($"Cannot load file '{fileName}' to '{targetType.FullName}'");
  69. foreach (var property in shadow.GetType().GetProperties())
  70. {
  71. if (target.GetType().GetProperties().Any(x => x.Name == property.Name && property.GetValue(shadow) != null))
  72. {
  73. if (property.GetType().IsClass && property.PropertyType.Assembly.FullName == targetType.Assembly.FullName)
  74. {
  75. var mapMethod = typeof(Binder).GetMethod("LoadTo");
  76. var genericMethod = mapMethod?.MakeGenericMethod(property.GetValue(shadow).GetType());
  77. var obj2 = genericMethod.Invoke(null, new object[] { property.GetValue(shadow), JsonSerializer.Serialize(property.GetValue(shadow)) });
  78. foreach (var property2 in obj2.GetType().GetProperties())
  79. {
  80. if (property2.GetValue(obj2) != null)
  81. {
  82. property.GetValue(target).GetType().GetProperty(property2.Name).SetValue(property.GetValue(target), property2.GetValue(obj2));
  83. }
  84. }
  85. }
  86. else if (property.CanWrite)
  87. {
  88. property.SetValue(target, property.GetValue(shadow));
  89. }
  90. }
  91. }
  92. }
  93. public void LoadFromStringTo(string jsonString, object target, Type targetType)
  94. {
  95. if (targetType == null)
  96. throw new ArgumentNullException(nameof(targetType));
  97. if (target == null)
  98. throw new ArgumentNullException(nameof(target));
  99. var shadow = LoadFromString(jsonString, targetType);
  100. foreach (var property in shadow.GetType().GetProperties())
  101. {
  102. if (target.GetType().GetProperties().Any(x => x.Name == property.Name && property.GetValue(shadow) != null))
  103. {
  104. if (property.GetType().IsClass && property.PropertyType.Assembly.FullName == targetType.Assembly.FullName)
  105. {
  106. var mapMethod = typeof(Binder).GetMethod("LoadFromStringTo");
  107. var genericMethod = mapMethod.MakeGenericMethod(property.GetValue(shadow).GetType());
  108. var obj2 = genericMethod.Invoke(null, new object[] { property.GetValue(shadow), JsonSerializer.Serialize(property.GetValue(shadow)) });
  109. foreach (var property2 in obj2.GetType().GetProperties())
  110. {
  111. if (property2.GetValue(obj2) != null)
  112. {
  113. property.GetValue(target).GetType().GetProperty(property2.Name).SetValue(property.GetValue(target), property2.GetValue(obj2));
  114. }
  115. }
  116. }
  117. else if (property.CanWrite)
  118. {
  119. property.SetValue(target, property.GetValue(shadow));
  120. }
  121. }
  122. }
  123. }
  124. public void LoadTo<TObject>(string fileName, TObject target)
  125. {
  126. LoadTo(fileName, target, typeof(TObject));
  127. }
  128. public void Save<TObject>(string fileName, TObject bindingObject)
  129. {
  130. if (string.IsNullOrEmpty(fileName))
  131. throw new ArgumentNullException(nameof(fileName));
  132. if (bindingObject==null)
  133. throw new ArgumentNullException(nameof(bindingObject));
  134. var configuration = JsonSerializer.SerializeToUtf8Bytes(bindingObject,SerializerOptions);
  135. using (var writer = _fileSystem.File.Create(fileName))
  136. {
  137. writer.Write(configuration);
  138. writer.Flush();
  139. }
  140. }
  141. public string SaveToString<TObject>(TObject bindingObject)
  142. {
  143. if (bindingObject==null)
  144. throw new ArgumentNullException(nameof(bindingObject));
  145. return JsonSerializer.Serialize(bindingObject,bindingObject.GetType());
  146. }
  147. }
  148. }