JsonPatch学习
网址 http://jsonpatch.com/
参考资料 https://docs.microsoft.com/zh-cn/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1
jsonpatch 个人感觉就是简化修改接口,就像给接口传个命令一样, replace Age 30;replace 就像命令, Age 就是参数,要修改的字段, 30 就是具体修改的值,jsonpatch 是通过json的方式来传递命令的,基本就是对json的 操作,增改删,
支持的语言也比较广泛,js 用法 http://jsonpatchjs.com/
例如 我们在QQ 中设置资料的时候, 是没有保存按钮的,选一个 或者编辑 都会 更新的,这种功能,我们不可能每次小改动就传递一个很大的实体去服务端修改,jsonpatch 就解决了这个问题
[{"op":"replace","path":"isopen","value":"true"}] 这个就即搞定,
页面是没有保存按钮的,但是点击复选框等都会保存我们的操作。
安装2个包
Microsoft.AspNetCore.JsonPatch
Microsoft.AspNetCore.Mvc.NewtonsoftJson
注册
services.AddControllers().AddNewtonsoftJson();
准备实体类和API接口
1 [ApiController] 2 [Route("jsonpatch")] 3 public class JsonPatchController : ControllerBase 4 { 5 public static List<User> _list; 6 private readonly ILogger<JsonPatchController> _logger; 7 8 public JsonPatchController(ILogger<JsonPatchController> logger) 9 {10 _logger = logger;11 _list = new List<User>();12 13 _list.Add(new User { Address=new List<Address> { new Address { City="广州", Group="一组" } }, Id=1, Name="jet1" });14 _list.Add(new User { Address = new List<Address> { new Address { City = "深圳", Group = "2组" } }, Id = 2, Name = "jet2" });15 _list.Add(new User { Address = new List<Address> { new Address { City = "西安", Group = "3组" } }, Id = 3, Name = "jet3" });16 17 18 }19 [Route("[action]/{id}")]20 [HttpPatch]21 public IActionResult UserOperation(int id, [FromBody] JsonPatchDocument<User> userDoc)22 {23 if (userDoc != null)24 {25 var user =_list.Where(x=>x.Id== id).FirstOrDefault();26 userDoc.ApplyTo(user, ModelState);27 if (!ModelState.IsValid)28 {29 return BadRequest(ModelState);30 }31 //context.savechange()32 return new ObjectResult(user);33 }34 else35 {36 return BadRequest(ModelState);37 }38 }39 40 41 }42 43 44 public class User45 {46 public int Id { get; set; }47 public string Name { get; set; }48 public List<Address> Address { get; set; }49 }50 public class Address51 {52 public string City { get; set; }53 public string Group { get; set; }54 }
View Code
postman 请求, Content-Type :application/json-patch json
add
1 [ 2 { 3 "op": "add", 4 "path": "/Address/-", 5 "value": { 6 "City":"咸阳" 7 } 8 }, 9 {10 "op": "add",11 "path": "/Address/-",12 "value": {13 "City":"宝鸡"14 }15 }16 17 ]
View Code
remove
1 [ 2 { 3 "op": "remove", 4 "path": "/Address/", 5 "value": { 6 "City":"广州" 7 } 8 } 9 10 ]
View Code
replace
1 [ 2 { 3 "op": "replace", 4 "path": "/Address/-", 5 "value": { 6 "City":"湛江" 7 } 8 } 9 10 ]
View Code
移动操作 将城市移动到了user name
1 [2 {3 "op": "move",4 "from":"/Address/0/City",5 "path": "/Name"6 }7 8 ]
View Code
还有 copy test
test
操作通常用于在发生并发冲突时阻止更新。