一、場景簡述
在寫後端返回JSON數據到前端的時候,遇到了前端一直無法獲得後端傳輸的數據,但實際已經後端已經傳輸到前端了。在看前端獲取到後端返回的數據的時候發現JSON中含有反斜槓,如下圖
想必一定是這個轉義符導致前端顯示數據失敗。
二、解決方案
筆者一開始用document.toJson().replace("\"","'")將反斜槓+雙引號轉換成單引號,但無果。
筆者就用了import net.sf.json.JSONArray;包下的JSONArray.fromObject(list)實現了,具體實現如下
1、首先maven添加依賴
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
2、具體後端測試代碼
public JSONObject test(@RequestParam(defaultValue="10")int pageSize, @RequestParam(defaultValue
="0")int pageNumber){
List<String> list = new ArrayList();
JSONObject jsonobj = new JSONObject();
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("mongodb數據庫名");
MongoCollection<Document> collection = mongoDatabase.getCollection("mongodb集合名");
//獲取mongodb中符合條件的document
FindIterable<Document> findIterable = collection.find().skip(pageNumber).limit(pageSize);
//遍歷
for (Document document : findIterable) {
//向list中添加符合條件的docement
list.add(document.toJson());
}
//處理了反斜槓問題
JSONArray jarr = JSONArray.fromObject(list);
//分頁限制打印
System.out.println(pageNumber);
System.out.println(pageSize);
jsonobj.put("rows",jarr);
jsonobj.put("total",4);
return jsonobj;
}
查看下返回給前端的JSON
可以看到已經沒有反斜槓了,問題解決,前端數據顯示成功