如何基于com.github.fge.jsonpatch构建JSON-Patch字符串负载调用PATCH接口
解决方法
不用手动拼接JSON字符串,直接利用com.github.fge.jsonpatch库的JsonPatch类结合JSON序列化工具(比如Jackson)就能生成你需要的格式:
步骤1:将操作集合转为JsonPatch实例
把你创建的JsonPatchOperation实例放到列表中,通过JsonPatch.fromOperations()方法生成JsonPatch对象:
import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchOperation; import com.github.fge.jsonpatch.ReplaceOperation; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Arrays; import java.util.List; // 创建单个补丁操作 JsonPatchOperation replaceName = new ReplaceOperation(new JsonPointer("/name"), new ObjectMapper().valueToTree("John")); JsonPatchOperation replaceSubject = new ReplaceOperation(new JsonPointer("/subject"), new ObjectMapper().valueToTree("Science")); // 收集操作并创建JsonPatch List<JsonPatchOperation> operations = Arrays.asList(replaceName, replaceSubject); JsonPatch patch = JsonPatch.fromOperations(operations);
步骤2:序列化JsonPatch为JSON字符串
用Jackson的ObjectMapper把JsonPatch对象序列化成带格式的JSON字符串:
ObjectMapper mapper = new ObjectMapper(); try { // 生成格式化后的JSON字符串(和示例格式一致) String patchJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(patch); // 输出结果就是你需要的数组格式 System.out.println(patchJson); } catch (Exception e) { e.printStackTrace(); }
补充说明
JsonPatch类本身实现了JSON序列化接口,序列化后会自动生成符合RFC 6902标准的JSON-Patch数组格式- 如果项目用Gson代替Jackson,也可以用
new GsonBuilder().setPrettyPrinting().create().toJson(patch)来生成格式化字符串
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

