我试图运行以下代码

Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();

JSONArray data = new JSONArray();
for (Object obj : result) {
    JSONArray row = new JSONArray();
    User user = (User) obj;
    row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
    data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();


两个jsonResponse的toString函数的结果如下:

{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}

{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}


我想从第一个json响应中删除[和之后]之前的“符号,就像第二个一样(我注意到在将数组放入jsonResponse对象之后,添加了”)。我怎样才能做到这一点?

最佳答案

由于您首先将“结果”转换为字符串,然后将其添加到aaData中,因此它将像字符串一样以引号结尾。如果您只想删除引号,则可以在第2行中执行以下操作:

String json = "##" + gson.toJson(result) + "##";


而这在第8行中:

jsonResponse.toString().replace("\"##", "").replace("##\"","");


(当然,您需要选择“引号” ##,以使其永远不会在其他任何数据中显示为实际的字符串内容)

但是更干净的解决方案(尽管可能更慢)可能是通过将第2行更改为以下内容将String转换为实际的JSONObject:

JSONObject json = new JSONObject(gson.toJson(result));

10-08 06:48