Gson toJson()的使用
为了返回layui中table所需要的数据格式可以使用toJson函数。需要导入gson.jar
首先需要一个类来定义数据结构
package utils; import Data.ArticleData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ToJsonCool { private String code; private String msg; private String count; private ArrayList<HashMap<String,String>> data; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } public ToJsonCool() { } public ToJsonCool(String code, String msg, String count, ArrayList<HashMap<String, String>> data) { this.code = code; this.msg = msg; this.count = count; this.data = data; } public ArrayList<HashMap<String, String>> getData() { return data; } public void setData(ArrayList<HashMap<String, String>> data) { this.data = data; } }
listarticledata=new ArrayList<ArticleData>(); listarticledata=articleDataDao.qrFindCheckSend(); listMapJson=new ArrayList<HashMap<String,String>>(); for(int i=0;i<listarticledata.size();i++){ mapJson= new HashMap<String, String>(); mapJson.put("a_id",listarticledata.get(i).getA_id()); mapJson.put("a_title",listarticledata.get(i).getA_title()); mapJson.put("a_key",listarticledata.get(i).getA_key()); mapJson.put("a_time",listarticledata.get(i).getA_time()); mapJson.put("a_man",listarticledata.get(i).getA_man()); mapJson.put("a_main_text",listarticledata.get(i).getA_main_text()); listMapJson.add(mapJson); } Gson gson=new Gson(); String str=null; str=gson.toJson(listarticledata); toJsonCool=new ToJsonCool("0","",listarticledata.size()+"",listMapJson); str=gson.toJson(toJsonCool);
这样就可以转换为layui所需要的格式
- {
- "code": 0,
- "msg": "",
- "count": 1000,
- "data": [{}, {}]
- }