JSONObject 可以將java對象轉換成json格式,用於處理ajax請求或者做app是與前台的交互.
但是Date類型的也會做轉換,很多時候我們是不想將日期的年月日分別轉換成json的.可以通過配置的方式按自己的設置將日期轉換.
廢話不多說:
/** * 把字段中有Date類型的對象放到json時,將date類型按照固定格式轉換 */ public static void jsonUtil(JSONObject jo,Object object,String key){ JsonConfig jConfig = new JsonConfig(); jConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); //將查詢結轉換為json,放到json中 jo.put(key, JSONObject.fromObject(object,jConfig).toString()); }
注冊日期格式的類:----僅僅是設置了一下Date轉換成string時的fmt
package ec.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; /** * Bean轉換為JSON相時將Date轉換成String * @author zlc * @Date 2016-4-19 * */ public class JsonDateValueProcessor implements JsonValueProcessor { private String datePattern = "yyyy-MM-dd HH:mm:ss"; public JsonDateValueProcessor() { super(); } public JsonDateValueProcessor(String format) { super(); this.datePattern = format; } public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value); } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return process(value); } private Object process(Object value) { try { if (value instanceof Date) { SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK); return sdf.format((Date) value); } return value == null ? "" : value.toString(); } catch (Exception e) { return ""; } } public String getDatePattern() { return datePattern; } public void setDatePattern(String pDatePattern) { datePattern = pDatePattern; } }
這樣吧對象轉換成json的時候就不會講Date類型的對象分別將年月日當做屬性來轉換了.
另外也可以用<%@page import="net.sf.json.JSONArray"%> JSONArray 來轉換:
List<View_oa_notice> oaUserList = (List<View_oa_notice>)request.getAttribute("noticeList"); jConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); JSONArray j = JSONArray.fromObject(oaUserList,jConfig); PrintWriter pw = response.getWriter(); pw.write(j.toString());