后台返回JSON关于日期的格式化

时间:2023-03-08 16:16:04

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());