錯誤做法
map.put("childNodes", "[" + hmap() + "]"); // 字符串拼接,產生雙引號轉義
json.put("childNodes", "[" + jsonArray.toString().replace("\"", "'") + "]"); // 手動替換,非標準
正確做法:直接操作 JSONArray
JSONObject root = new JSONObject();
root.put("id", "root");
root.put("text", "根節點");
JSONArray children = new JSONArray();
JSONObject child = new JSONObject();
child.put("id", "org1");
child.put("text", "軟件");
child.put("showCheck", true);
children.put(child);
root.put("childNodes", children); // 直接放入 JSONArray,序列化時自動生成正確結構
String jsonStr = root.toString(); // {"id":"root","text":"根節點","childNodes":[{"id":"org1","text":"軟件","showCheck":true}]}
Gson 等效
Gson gson = new Gson();
Map<String, Object> map = new HashMap<>();
map.put("childNodes", List.of(Map.of("id","org1","text","軟件","showCheck",true)));
String json = gson.toJson(map);