老规矩,概念的东西不再此处体现,baidu即可自行解决,直入主题,动手第一。
导入所需的jar文件
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-patch</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
创建demo文件
JsonPatchDemo.java
package com.szl.demo.szldemo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonpatch.JsonPatch; public class JsonPatchDemo { public static void main(String[] args) { String origin = "{\"userName\":\"Captain America\", \"userAccount\":\"qweewq\", \"userPwd\":\"333777\"}"; String patch = "[" + "{\"op\":\"replace\", \"path\":\"/userName\", \"value\":\"Ant Man\"}," + "{\"op\":\"add\", \"path\":\"/level\", \"value\":\"9\"}," + "{\"op\":\"replace\", \"path\":\"/userPwd\", \"value\":\"xxxxxx\"}" + "]"; String afterJson = patchApplication(origin, patch); System.out.println(afterJson); } /** * @param origin 原JSON * @param patch patch信息 * @return */ public static String patchApplication(String origin, String patch) { try { ObjectMapper objectMapper = new ObjectMapper(); // 将原json转为JsonNode JsonNode originJson = objectMapper.readTree(origin); // 将patch json转为 JsonNode JsonNode patchJson = objectMapper.readTree(patch); // 将patch形式的json转为 JsonPatch JsonPatch patcher = JsonPatch.fromJson(patchJson); // patch应用替换原JSON JsonNode afterJson = patcher.apply(originJson); return afterJson.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } }
是不是很简单,就是这么easy,以下是jsonPatch的官网,版本也在不断的更新,可以持续关注。