您的位置:首页 > Web前端 > JavaScript

responseBody之Date转json

2017-07-08 16:44 387 查看
1.在controller类中添加代码

@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true)); /*true:允许输入空值,false:不能为空值 */


2.下面的配置作用与springmvc的responseBody也就是Jackson

DateTimeFormat是对提交上来的参数格式化为日期
JsonSerialize是把Date转成json转出去

javabean中的配置
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonSerialize(using=JsonDateSerializer.class)
public Date getCreateTime() {
return this.createTime;
}

时间转换时间类
public class JsonDateSerializer extends JsonSerializer<Date> {
private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String value = dateFormat.format(date);
gen.writeString(value);
}
}


3.解决SpringMVC全局日期格式华配置

转换类
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

xml中的配置
<mvc:annotation-driven conversion-service="conversionService" />

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.doje.XXX.web.DateConverter" />
</list>
</property>
</bean>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: