Browse Source

编写JsonPatchHelper,实现对对象进行路径直接操作Add, Remove,Replace,Move,Copy等操作。

CrazyIter 5 years ago
parent
commit
6e426539e0

+ 46 - 0
TEAMModelOS.SDK/Helper/Common/JsonHelper/JsonPatchHelper.cs

@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Microsoft.AspNetCore.JsonPatch;
+using Microsoft.AspNetCore.JsonPatch.Operations;
+namespace System
+{
+    public static class JsonPatchHelper
+    {
+        public static T Add<T>(this T t, string path, object value) where T : class
+        {
+            JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
+            jsonPatch.Operations.Add(new Operation<T>("add", path, null, value));
+            jsonPatch.ApplyTo(t);
+            return t;
+        }
+        public static T Remove<T>(this T t, string path) where T : class
+        {
+            JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
+            jsonPatch.Operations.Add(new Operation<T>("remove", path, null, null));
+            jsonPatch.ApplyTo(t);
+            return t;
+        }
+        public static T Replace<T>(this T t, string path, object value) where T : class
+        {
+            JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
+            jsonPatch.Operations.Add(new Operation<T>("replace", path, null, value));
+            jsonPatch.ApplyTo(t);
+            return t;
+        }
+        public static T Move<T>(this T t, string from, string path) where T : class
+        {
+            JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
+            jsonPatch.Operations.Add(new Operation<T>("move", path, from));
+            jsonPatch.ApplyTo(t);
+            return t;
+        }
+        public static T Copy<T>(this T t, string from, string path) where T : class
+        {
+            JsonPatchDocument<T> jsonPatch = new JsonPatchDocument<T>();
+            jsonPatch.Operations.Add(new Operation<T>("copy", path, from));
+            jsonPatch.ApplyTo(t);
+            return t;
+        }
+    }
+}

+ 1 - 0
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -19,6 +19,7 @@
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+    <PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="3.1.2" />
     <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
     <PackageReference Include="Microsoft.Azure.CosmosDB.BulkExecutor" Version="2.4.1-preview" />
     <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.9.2" />