Json解析

来源:互联网 发布:最优化算法pdf 编辑:程序博客网 时间:2024/06/06 03:41
$(function(){getAllEmp();function getAllEmp(){                $.getJSON("${basePath}/EmpAction.do?method=list",                function (data) {                    var s = "";                                        $("#emp tr:eq(0)").siblings().remove();                    $.each(data, function (index, emp) {                  var mgrName=emp.mgr.ename;                        if(emp.mgr==""){                  mgrName="没有上级";                  }                        s += "<tr>";                        s += "<td>" + emp.empNo + "</td>";                        s += "<td>" + emp.ename + "</td>";                        s += "<td>" + emp.job + "</td>";                        s += "<td>" + mgrName+ "</td>";                        s += "<td>" + emp.hiredate + "</td>";                        s += "<td>" + emp.sal + "</td>";                        s += "<td>" + emp.comm + "</td>";                        s += "<td>" + emp.dept.dName+ "</td>";                        s += "</tr>";                    });                    $("#emp").append(s);                });}})

后台代码

public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {List<Emp> empList = empService.findAll();JsonConfig cfg = new JsonConfig();/* 过滤关联,避免死循环 * emp和dept中有双向关联,要将dept中emps属性过滤 * 前台需要显示dept部门信息,不能直接过滤dept * */cfg.setJsonPropertyFilter(new PropertyFilter() {public boolean apply(Object source, String name, Object value) {if (name.equals("emps")) {return true;} else {return false;}}});// 设置json的懒加载cfg.setExcludes(new String[] { "handler", "hibernateLazyInitializer" });/* * 设置null值转化 emp中有一个员工是没有上级的,所以emp.mgr为null,  * 前台json则不能显示。所以要将null转化为""字符串。然后在前台判断,如果emp.mgr=="",再将emp.mgr.ename="没有上级" */cfg.registerDefaultValueProcessor(Emp.class, new DefaultValueProcessor() {public Object getDefaultValue(Class type) {return "";}});/* * 注册日期转化 * 按照指定的格式yyyy-MM-dd * */cfg.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {private SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");public Object processArrayValue(Object value, JsonConfig jsonConfig) {return null;}public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {if (value == null) {return "";} else {return sd.format(value);}}});JSONArray json = JSONArray.fromObject(empList, cfg);response.getWriter().print(json.toString());System.out.println(json.toString());return null;}


原创粉丝点击