springboot中JSONObject遍歷并替換部分json值
使用場景
如何修改JSONObject 的值,如何替換json中的部分內容,比如檢查報告我們再數據庫存的是json格式的字符串varchar,然后前端傳來確認更新報告的json,后臺接口需要將前端傳來的json里面的內容更新到后臺數據庫(當然,前端傳來的不一定是完整的字符串,可能是一個,兩個,總之只是部分不是全部)。這個時候就需要使用這個方案了。
代碼展示
@PutMapping("/result/{checkNum}") public ApiReturnObject update(@PathVariable String checkNum,String dataStr) { //從數據庫查出duix Result result= resultReposity.findByCheckNum(checkNum); //接收的參數 JSONObject jsonObj=JSON.parseObject(dataStr); JSONObject originObj=JSON.parseObject(result.getCheckresult()); //單個替換 //originObj.put("AGE", jsonObj.get("AGE")); //遍歷替換json里面的值 for (String key:jsonObj.keySet()) { originObj.put(key, jsonObj.get(key)); } //轉化為jsonString result.setCheckresult(originObj.toJSONString()); //更新狀態(tài) result.setStatus("1"); //保存 resultReposity.save(result); }
JSON操作講解
put可以強制更新json里面的值
JSONObject json = JSON.parseObject("{val: 123}"); System.out.println("======before====="); System.out.println("size: " + json.size()); System.out.println("val: " + json.get("val")); //直接put相同的key json.put("val", 234); System.out.println("======after======"); System.out.println("size: " + json.size()); System.out.println("val: " + json.get("val"));
結果
======before=====
size: 1
val: 123
======after======
size: 1
val: 234
JSONObject.keySet()可以遍歷json所有的key值
for (String key:jsonObj.keySet()) { originObj.put(key, jsonObj.get(key)); }
到此這篇關于springboot中JSONObject遍歷并替換部分json值的文章就介紹到這了,更多相關JSONObject遍歷并替換json內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring?Boot?整合?Fisco?Bcos部署、調用區(qū)塊鏈合約的案例
本篇文章介紹?Spring?Boot?整合?Fisco?Bcos?的相關技術,最最重要的技術點,部署、調用區(qū)塊鏈合約的工程案例,本文通過流程分析給大家介紹的非常詳細,需要的朋友參考下吧2022-01-01