Binder.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 shadowValue = property.GetValue(shadow);
  77. var shadowType = property.GetValue(shadow)?.GetType() ?? property.PropertyType;
  78. var genericMethod = mapMethod?.MakeGenericMethod(shadowType);
  79. var obj2 = genericMethod?.Invoke(null, new object?[] { shadowValue, JsonSerializer.Serialize(property.GetValue(shadow)) });
  80. if (obj2 != null)
  81. {
  82. foreach (var property2 in obj2.GetType().GetProperties())
  83. {
  84. if (property2.GetValue(obj2) != null)
  85. {
  86. (property.GetValue(target)?.GetType() ?? property.PropertyType).GetProperty(
  87. property2.Name)!.SetValue(property.GetValue(target), property2.GetValue(obj2));
  88. }
  89. }
  90. }
  91. }
  92. else if (property.CanWrite)
  93. {
  94. property.SetValue(target, property.GetValue(shadow));
  95. }
  96. }
  97. }
  98. }
  99. public void LoadFromStringTo(string jsonString, object target, Type targetType)
  100. {
  101. if (targetType == null)
  102. throw new ArgumentNullException(nameof(targetType));
  103. if (target == null)
  104. throw new ArgumentNullException(nameof(target));
  105. var shadow = LoadFromString(jsonString, targetType);
  106. if(shadow == null) throw new InvalidOperationException($"Cannot load object ({targetType.FullName}) from json string.");
  107. foreach (var property in shadow.GetType().GetProperties())
  108. {
  109. if (target.GetType().GetProperties().Any(x => x.Name == property.Name && property.GetValue(shadow) != null))
  110. {
  111. if (property.GetType().IsClass && property.PropertyType.Assembly.FullName == targetType.Assembly.FullName)
  112. {
  113. var mapMethod = typeof(Binder).GetMethod("LoadFromStringTo");
  114. var shadowType = property.GetValue(shadow)?.GetType() ?? property.PropertyType;
  115. var genericMethod = mapMethod?.MakeGenericMethod(shadowType);
  116. var obj2 = genericMethod?.Invoke(null, new object?[] { property.GetValue(shadow), JsonSerializer.Serialize(property.GetValue(shadow)) });
  117. if (obj2 != null)
  118. {
  119. foreach (var property2 in obj2.GetType().GetProperties())
  120. {
  121. if (property2.GetValue(obj2) != null)
  122. {
  123. property?.GetValue(target)?.GetType()?.GetProperty(property2.Name)?
  124. .SetValue(property.GetValue(target), property2.GetValue(obj2));
  125. }
  126. }
  127. }
  128. }
  129. else if (property.CanWrite)
  130. {
  131. property.SetValue(target, property.GetValue(shadow));
  132. }
  133. }
  134. }
  135. }
  136. public void LoadTo<TObject>(string fileName, TObject target)
  137. {
  138. if (target == null)
  139. throw new ArgumentNullException(nameof(target));
  140. LoadTo(fileName, target, typeof(TObject));
  141. }
  142. public void Save<TObject>(string fileName, TObject bindingObject)
  143. {
  144. if (string.IsNullOrEmpty(fileName))
  145. throw new ArgumentNullException(nameof(fileName));
  146. if (bindingObject==null)
  147. throw new ArgumentNullException(nameof(bindingObject));
  148. var configuration = JsonSerializer.SerializeToUtf8Bytes(bindingObject,SerializerOptions);
  149. using (var writer = _fileSystem.File.Create(fileName))
  150. {
  151. writer.Write(configuration);
  152. writer.Flush();
  153. }
  154. }
  155. public string SaveToString<TObject>(TObject bindingObject)
  156. {
  157. if (bindingObject==null)
  158. throw new ArgumentNullException(nameof(bindingObject));
  159. return JsonSerializer.Serialize(bindingObject,bindingObject.GetType());
  160. }
  161. }
  162. }