SpringMVC配置@ResponseBody注解时会自动转换为JSON字符串,可像此一样自定义Date或其他类转JSON的格式
代码实现
package data;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
* <p>Description: ResopnseBody 自动转 JSON 时,特殊类做转换</p>
*
* @author c332030
* @version 1.0
* @date 2019-3-21 10:38
*/
@Component
public class JSONDataFormat extends ObjectMapper {
protected Logger logger = LoggerFactory.getLogger(JSONDataFormat.class);
private static final ThreadLocal<DateFormat> dateTimeFormatThreadLocal
= new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat(defaultDatePattern);
}
};
public JSONDataFormat() {
CustomSerializerFactory factory = new CustomSerializerFactory();
this.setSerializerFactory(factory);
dateTimeFormat(factory);
}
/**
* 方法用途: 日期格式化
* 实现步骤:
* @param factory
* @return void
*/
public void dateTimeFormat(CustomSerializerFactory factory) {
factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(
Date date, JsonGenerator jsonGenerator, SerializerProvider provider
) throws IOException {
jsonGenerator.writeString(dateTimeFormatThreadLocal.get().format(date));
}
});
}
}
Spring配置文件
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<!-- 数据格式化 -->
<property name="objectMapper" ref="JSONDataFormat"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>