map 转json数据并返给前端,前端可以用JSON.parse()序列化
import java.util.HashMap;import java.util.Mappublic class MapToJson { public static String toJson(boolean success,String key,Integer val){ MapjsonMap = new HashMap (); jsonMap.put(key,val); return toJson(success,jsonMap); } public static String toJson(boolean success,Map jsonMap){ StringBuffer buffer = new StringBuffer(); if (success){ buffer.append("{\"success\":true,\"data\":["); }else{ buffer.append("{success:false}"); } if (jsonMap.size() >0){ for (String key:jsonMap.keySet()){ if(!key.equals(("class"))){ buffer.append("{"+'"'+key+'"' + ":"+jsonMap.get(key)+"},"); } } buffer.deleteCharAt(buffer.length()-1); } buffer.append("]}"); return buffer.toString(); }}复制代码
在网上搜搜到一位老哥的方法,但是输出的前端解析不了,最后重新检查,发现返回的json格式不正确,所以重新改了格式,然后就能解析,下面是前端代码
let fragment = document.createDocumentFragment();let total = 0;Tools.ajax({ url:'/cart', data:{id:1}, type:'post', success:function (req) { let rel = JSON.parse(req); console.log(typeof (req)); console.log(req); console.log(rel); for(let i = 0; i < rel.data.length; i++){ for(key in rel.data[i]); let div = document.createElement("div"); div.innerHTML = "商品名称:"+key+"商品数量:"+rel.data[i][key]+""; total+=rel.data[i][key]; fragment.appendChild(div) } let cart = document.querySelector(".cart"); cart.appendChild(fragment); console.log(total); } })复制代码