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

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

Latest stable 2.x version

  • Deployable jars (core jars; some of more commonly used extensions
    • Core (release notes)

    • Annotations (release notes)

    • Databind (release notes)

接收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统一格式化


	
		
			
				
					
						
							
								
							
						
					
				
			
		
	


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




你可能感兴趣的:(Spring MVC json接口 Date (java.util.Date) 日期格式化)