兩個json格式的字符串拼接,直接上代碼
String d="{\"username1\":\"zhangsan\",\"password1\":\"zhangsan\"}"; JSONObject json4=JSONObject.fromObject(d); String e="{\"username2\":\"lisi\",\"password2\":\"lisi\"}"; JSONObject json5=JSONObject.fromObject(e); JSONObject json6 = new JSONObject(); json6.putAll(json4); json6.putAll(json5); System.out.println(json6);
首先是通過JSONObject.fromObject()方法把字符串轉化為json,然后新建一個json,把兩個json放入到這個新json里面,然后這個新的json就是之前兩個json合並之后的結果了。
合並的規則是:當后面的json的key存在前面的json時,后面的key的值會覆蓋前面的key的值,否則就會字節拼接到后面。
附上前面代碼的結果;
參考:https://www.imooc.com/wenda/detail/481214