Java map轉JSON

Visupervi Reborn發表於2019-02-22

map 轉json資料並返給前端,前端可以用JSON.parse()序列化

import java.util.HashMap;
import java.util.Map
public class MapToJson {
   public static String toJson(boolean success,String key,Integer val){
      Map<String,Integer> jsonMap = new HashMap<String, Integer>();
      jsonMap.put(key,val);
      return toJson(success,jsonMap);
  }
   public static String toJson(boolean success,Map<String,Integer> 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 = "<span>商品名稱:"+key+"</span><span>商品數量:"+rel.data[i][key]+"</span>";
            total+=rel.data[i][key];
        fragment.appendChild(div)
    }

    let cart = document.querySelector(".cart");
    cart.appendChild(fragment);
    console.log(total);
   }
 })複製程式碼

相關文章