JSON中时间对象的输出格式是怎么定义的

如题所述

默认是转成timestamps形式的,通过下面方式可以取消timestamps。
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

这样将使时间生成使用所谓的use a [ISO-8601 ]-compliant notation, 输出类似如下格式的时间: "1970-01-01T00:00:00.000+0000".
当然也可以自定义输出格式:

objectMapper.getSerializationConfig().setDateFormat(myDateFormat);

myDateFormat对象为java.text.DateFormat,具体使用清查java API
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-05-27
package cn.com.unutrip.java.json;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
* 关于时间的json处理器的应用
*
* @author longgangbai
*
*/
public class DateJsonValueProcessor implements JsonValueProcessor {

public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private DateFormat dateFormat;

public DateJsonValueProcessor(String datePattern) {
if (null == datePattern)
dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
else
dateFormat = new SimpleDateFormat(datePattern);
}

public Object processArrayValue(Object arg0, JsonConfig arg1) {
return process(arg0);
}

public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
return process(arg1);
}

private Object process(Object value) {
return dateFormat.format((Date) value);
}
}
(2)在配置JSONConfig中添加注册:
/**
* JSON 时间解析器具
*
* @param datePattern
* @return
*/
public static JsonConfig configJson(String datePattern) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[] { "" });
jsonConfig.setIgnoreDefaultExcludes(false);
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(datePattern));
return jsonConfig;
}
相似回答