JsonPatchHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.AspNetCore.JsonPatch;
  5. using Microsoft.AspNetCore.JsonPatch.Operations;
  6. namespace System
  7. {
  8. public static class JsonPatchHelper
  9. {
  10. public static T Add<T>(this T t, string path, object value) where T : class
  11. {
  12. JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
  13. jsonPatch.Operations.Add(new Operation<T>("add", path, null, value));
  14. jsonPatch.ApplyTo(t);
  15. return t;
  16. }
  17. public static T Remove<T>(this T t, string path) where T : class
  18. {
  19. JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
  20. jsonPatch.Operations.Add(new Operation<T>("remove", path, null, null));
  21. jsonPatch.ApplyTo(t);
  22. return t;
  23. }
  24. public static T Replace<T>(this T t, string path, object value) where T : class
  25. {
  26. JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
  27. jsonPatch.Operations.Add(new Operation<T>("replace", path, null, value));
  28. jsonPatch.ApplyTo(t);
  29. return t;
  30. }
  31. public static T Move<T>(this T t, string from, string path) where T : class
  32. {
  33. JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
  34. jsonPatch.Operations.Add(new Operation<T>("move", path, from));
  35. jsonPatch.ApplyTo(t);
  36. return t;
  37. }
  38. public static T Copy<T>(this T t, string from, string path) where T : class
  39. {
  40. JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
  41. jsonPatch.Operations.Add(new Operation<T>("copy", path, from));
  42. jsonPatch.ApplyTo(t);
  43. return t;
  44. }
  45. }
  46. }