Binder.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. WriteIndented = isPrettyPrint,
  28. PropertyNameCaseInsensitive = true,
  29. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  30. MaxDepth = maxDepth
  31. };
  32. if (isIgnoringNullValues)
  33. jsonOpt.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  34. jsonOpt.Converters.Add(new JsonStringEnumConverter());
  35. SerializerOptions = jsonOpt;
  36. }
  37. public TObject? Load<TObject>(string fileName)
  38. {
  39. return (TObject?) Load(fileName, typeof(TObject));
  40. }
  41. public object? Load(string fileName, Type targetType)
  42. {
  43. if (targetType == null)
  44. throw new ArgumentNullException(nameof(targetType));
  45. if (string.IsNullOrEmpty(fileName))
  46. throw new ArgumentNullException(nameof(fileName));
  47. using (var reader = _fileSystem.File.OpenText(fileName))
  48. {
  49. var result = JsonSerializer.Deserialize(reader.ReadToEnd(),targetType, SerializerOptions);
  50. return result;
  51. }
  52. }
  53. public object? LoadFromString(string jsonString, Type targetType)
  54. {
  55. if (targetType == null)
  56. throw new ArgumentNullException(nameof(targetType));
  57. if (string.IsNullOrEmpty(jsonString))
  58. throw new ArgumentNullException(nameof(jsonString));
  59. var result = JsonSerializer.Deserialize(jsonString,targetType, SerializerOptions);
  60. return result;
  61. }
  62. public void LoadTo(string fileName, object target, Type targetType)
  63. {
  64. if (targetType == null)
  65. throw new ArgumentNullException(nameof(targetType));
  66. if (target == null)
  67. throw new ArgumentNullException(nameof(target));
  68. var shadow = Load(fileName, targetType);
  69. if (shadow == null) throw new InvalidOperationException($"Cannot load file '{fileName}' to '{targetType.FullName}'");
  70. foreach (var property in shadow.GetType().GetProperties())
  71. {
  72. if (target.GetType().GetProperties().Any(x => x.Name == property.Name && property.GetValue(shadow) != null))
  73. {
  74. if (property.GetType().IsClass && property.PropertyType.Assembly.FullName == targetType.Assembly.FullName)
  75. {
  76. var mapMethod = typeof(Binder).GetMethod("LoadTo");
  77. var shadowValue = property.GetValue(shadow);
  78. var shadowType = property.GetValue(shadow)?.GetType() ?? property.PropertyType;
  79. var genericMethod = mapMethod?.MakeGenericMethod(shadowType);
  80. var obj2 = genericMethod?.Invoke(null, new object?[] { shadowValue, JsonSerializer.Serialize(property.GetValue(shadow)) });
  81. if (obj2 != null)
  82. {
  83. foreach (var property2 in obj2.GetType().GetProperties())
  84. {
  85. if (property2.GetValue(obj2) != null)
  86. {
  87. (property.GetValue(target)?.GetType() ?? property.PropertyType).GetProperty(
  88. property2.Name)!.SetValue(property.GetValue(target), property2.GetValue(obj2));
  89. }
  90. }
  91. }
  92. }
  93. else if (property.CanWrite)
  94. {
  95. property.SetValue(target, property.GetValue(shadow));
  96. }
  97. }
  98. }
  99. }
  100. public void LoadFromStringTo(string jsonString, object target, Type targetType)
  101. {
  102. if (targetType == null)
  103. throw new ArgumentNullException(nameof(targetType));
  104. if (target == null)
  105. throw new ArgumentNullException(nameof(target));
  106. var shadow = LoadFromString(jsonString, targetType);
  107. if(shadow == null) throw new InvalidOperationException($"Cannot load object ({targetType.FullName}) from json string.");
  108. foreach (var property in shadow.GetType().GetProperties())
  109. {
  110. if (target.GetType().GetProperties().Any(x => x.Name == property.Name && property.GetValue(shadow) != null))
  111. {
  112. if (property.GetType().IsClass && property.PropertyType.Assembly.FullName == targetType.Assembly.FullName)
  113. {
  114. var mapMethod = typeof(Binder).GetMethod("LoadFromStringTo");
  115. var shadowType = property.GetValue(shadow)?.GetType() ?? property.PropertyType;
  116. var genericMethod = mapMethod?.MakeGenericMethod(shadowType);
  117. var obj2 = genericMethod?.Invoke(null, new object?[] { property.GetValue(shadow), JsonSerializer.Serialize(property.GetValue(shadow)) });
  118. if (obj2 != null)
  119. {
  120. foreach (var property2 in obj2.GetType().GetProperties())
  121. {
  122. if (property2.GetValue(obj2) != null)
  123. {
  124. property?.GetValue(target)?.GetType()?.GetProperty(property2.Name)?
  125. .SetValue(property.GetValue(target), property2.GetValue(obj2));
  126. }
  127. }
  128. }
  129. }
  130. else if (property.CanWrite)
  131. {
  132. property.SetValue(target, property.GetValue(shadow));
  133. }
  134. }
  135. }
  136. }
  137. public void LoadTo<TObject>(string fileName, TObject target)
  138. {
  139. if (target == null)
  140. throw new ArgumentNullException(nameof(target));
  141. LoadTo(fileName, target, typeof(TObject));
  142. }
  143. public void Save<TObject>(string fileName, TObject bindingObject)
  144. {
  145. if (string.IsNullOrEmpty(fileName))
  146. throw new ArgumentNullException(nameof(fileName));
  147. if (bindingObject==null)
  148. throw new ArgumentNullException(nameof(bindingObject));
  149. var configuration = JsonSerializer.SerializeToUtf8Bytes(bindingObject,SerializerOptions);
  150. using (var writer = _fileSystem.File.Create(fileName))
  151. {
  152. writer.Write(configuration);
  153. writer.Flush();
  154. }
  155. }
  156. public string SaveToString<TObject>(TObject bindingObject)
  157. {
  158. if (bindingObject==null)
  159. throw new ArgumentNullException(nameof(bindingObject));
  160. return JsonSerializer.Serialize(bindingObject,bindingObject.GetType());
  161. }
  162. }
  163. }