Spring MVC json接口 Date (java.util.Date) 日期格式化

本文介绍了如何在Spring MVC中处理JSON接口时,对`java.util.Date`进行格式化。通过引入Jackson库,展示了如何接收和返回日期参数。在接收Date参数时,利用了`@InitBinder`注解;对于返回的对象,文中提到了两种方法,一种是在具体日期字段上标注,仅影响单个JSON对象的日期格式,另一种可能是全局配置日期格式化方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用Spring MVC做app的接口,用到Jackson的3个jar包

Latest stable 2.x version

接收Date(java.util.Date)参数,使用@InitBinder

@Controller
public class TestController {
	
	@RequestMapping("/test.json")
	@ResponseBody
	public Test testJson(Integer i, Float f, String str, Date date) {
		Test test = new Test();
		test.setI( i!=null ? i : 1);
		test.setF( f!=null ? f : 2.0f);
		test.setStr( str!=null ? str : "test");
		test.setDate(date !=null ? date : new Date());
		return test;
	}
	
	@InitBinder  
	protected void initBinder(HttpServletRequest request,
		ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
	}
}


返回的对象Test.java(省略getter setter)

public class Test {
	private Integer i;
	private Float f;
	private String str;
	private Date date;
}



默认返回JSON对象中,date是timestamp格式,long型


{
    "i": 1,
    "f": 2,
    "str": "test",
    "date": 1390363200000
}



返回的date格式化

方法1:在Test.java中标注getDate方法,只对单个返回JSON对象生效

	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss", timezone="CET")
	public Date getDate() {
		return date;
	}

方法2:配置spring-config.xml,所有date统一格式化

<!-- 处理返回json日期时间格式 -->
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="objectMapper">
					<bean class="com.fasterxml.jackson.databind.ObjectMapper">
						<property name="dateFormat">
							<bean class="java.text.SimpleDateFormat">
								<constructor-arg value="yyyy-MM-dd HH:mm:ss" />
							</bean>
						</property>
					</bean>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>


{
    "i": 1,
    "f": 2,
    "str": "test",
    "date": "2010-12-31 18:01:01"
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值