Created
September 21, 2014 12:35
-
-
Save fuzhengwei/e0a972dd62c820367892 to your computer and use it in GitHub Desktop.
SpringMVC返回JSON数据时日期格式化问题
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.micmiu.demo.web.v1.utils; | |
import java.io.IOException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import org.codehaus.jackson.JsonGenerator; | |
import org.codehaus.jackson.JsonProcessingException; | |
import org.codehaus.jackson.map.JsonSerializer; | |
import org.codehaus.jackson.map.SerializerProvider; | |
/** | |
* 自定义返回JSON 数据格中日期格式化处理 | |
* 这类的代码都可以写在工具类里 | |
*/ | |
public class CustomDateSerializer extends JsonSerializer<Date> { | |
@Override | |
public void serialize(Date value, JsonGenerator jgen, | |
SerializerProvider provider) throws IOException, | |
JsonProcessingException { | |
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); | |
String formattedDate = formatter.format(value); | |
jgen.writeString(formattedDate); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//javabean对应属性的方法添加注解: | |
@JsonSerialize(using = CustomDateSerializer.class) | |
public Date getCreateDate() { | |
return createDate; | |
} | |
//就这么简单就可以实现返回的JSON数据中日期格式自动转换为:yyyy-MM-dd 的格式了。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
目录: | |
概述及场景 | |
测试环境 | |
解决方案 | |
[一]、概述及场景 | |
在运用SpringMVC框架开发时,可以直接在方法上添加注解 @ResponseBody 返回JSON数据,如果javabean的属性中包含 Date日期类型的数据,默认的转换格式并不是我们想要的 yyyy-MM-dd 这样的格式,那又如何实现这样的格式转化呢? | |
[二]、测试环境 | |
SpringMVC 3.2.0 | |
Jackson 1.7.1 | |
[三]、解决方案 | |
其实SpringMVC的JSON转换方法是利用了 Jackson 这个开源的第三方类库,它提供了一些自定义格式的方法。只要我们继承它的抽象类:public abstract class JsonSerializer<T>,并在相应的属性方法上添加指定注解:@JsonSerialize 即可实现。 | |
编写Date日志自定义转换类: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment