最常见的在实体类上配置

1

JsonFormat来源于jackson,Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。Jackson所依赖的jar包较少,简单易用并且性能也要相对高些,并且Jackson社区相对比较活跃,更新速度也比较快。 

注意:默认Spring  @RequestBody和@ResponseBody都是使用jackson来转化格式的。
 @JsonFormat(pattern=”yyyy-MM-dd”,timezone=”GMT+8”)
2
JSONField来源于fastjson,是阿里巴巴的开源框架,主要进行JSON解析和序列化。
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
下附上相关JSON的错误用法:
 private Date pwdLastSet;
 // JSONObject data=(JSONObject)JSON.toJSON(dataTable);//错误用法
 JSONObject data=JSONObject.parseObject(JSON.toJSONString(dataTable));//转JSon对象的正确用法 3
DateTimeFormat是spring自带的处理框架,主要用于将时间格式化。
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.nio.util.DateJsonSerialize;
@JsonSerialize(using = DateJsonSerialize.Date_YYYYMMDDHHMMSS.class)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
其他博客的内容介绍如下:
@JsonFormat用于将后台返回前台的Date变量转换为字符串类型;
@DateTimeFormat用于将前台传到后台字符串变量转换为Date类型。
@JsonFormat不仅可以完成后台到前台参数传递的类型转换,还可以实现前台到后台类型转换。
当content-type为application/json时,优先使用@JsonFormat的pattern进行类型转换。
而不会使用@DateTimeFormat进行类型转换。
个人理解,@JsonFormat注解的作用就是完成json字符串到java对象的转换工作,与参数传递的方向无关。
 
4
在Controller层使用比较少使用的方法
在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必须要手动配置, 自定义数据类型的绑定才能实现这个功能。
比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作
 @InitBinder
     public void initBinder(WebDataBinder binder) {
         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");       //有反应中间这句有时候会有问题,可能某些情况要注释。
 dateFormat.setLenient(false);
       //有反应中间这句有时候会有问题,可能某些情况要注释。
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
     }
 binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); 
其实还可以自己创建对应的
import org.springframework.beans.propertyeditors.PropertiesEditor;
 
public class DoubleEditor extends PropertiesEditor {  
    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        if (text == null || text.equals("")) {  
            text = "0";  
        }  
        setValue(Double.parseDouble(text));  
    }  
  
    @Override  
    public String getAsText() {  
        return getValue().toString();  
    }  
} 



	@InitBinder  
    protected void initBinder(WebDataBinder binder) {  
        binder.registerCustomEditor(double.class, new DoubleEditor());  

    } 
另外还可以直接继承的是
class org.springframework.beans.propertyeditors.PropertiesEditor extends java.beans.PropertyEditorSupport {补充一种另外的做法controllerAdvice标签
 
 
5
全局转化函数
MVCConfigurer上对应的
public void addFormatters(FormatterRegistry  registry){
registry.addFormatter(new DateFomatter("yyyy-MM-dd HH:mm:ss"));
}