@JsonFormat和@DateTimeFormat对Date格式化
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.pojo; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class User { private Long id; private String username; //用户名 private String password; //密码 private String phone; //手机号 private String email; //邮箱 private Date created; //创建日期 private Date updated; //修改日期
public Long getId() { return id; } public void setId(Long id) { this .id = id;}
public String getUsername() { return username;} public void setUsername(String username) { this .username = username;}
public String getPassword() { return password;} public void setPassword(String password) { this .password = password;}
public String getPhone() { return phone;} public void setPhone(String phone) { this .phone = phone;}
public String getEmail() { return email;} public void setEmail(String email) { this .email = email;}
public Date getCreated() { return created;} public void setCreated(Date created) { this .created = created;}
public Date getUpdated() { return updated;} public void setUpdated(Date updated) { this .updated = updated;} } |
一、@JsonFormat
控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@RequestMapping ( "/getdate" ) @ResponseBody public TbUser getdate() { TbUser user = new TbUser(); user.setId(1001l); user.setUsername( "zhangsan" ); user.setPassword( "1234567" ); user.setPhone( "15225969681" ); user.setEmail( "123@qq测试数据" ); user.setUpdated( new Date()); user.setCreated( new Date()); return user; } |
访问控制器在浏览器中输出的json格式如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15212559252","email":"123@qq测试数据","created":1545288773904,"updated":"1545288773904"}
可见created、updated这两个属性值是时间戳并不是[yyyy-MM-dd HH:mm:ss]格式,那怎么把日期类型格式化成我们想要的类型呢,其实很简单只需要在实体类的属性上加上**@JsonFormat**注解就行了。
1 2 3 4 |
@JsonFormat (pattern= "yyyy-MM-dd HH:mm:ss" ,timezone = "GMT+8" ) private Date created; @JsonFormat (pattern= "yyyy-MM-dd HH:mm:ss" ,timezone = "GMT+8" ) private Date updated; |
1 |
@JsonFormat (pattern=[yyyy-MM-dd],timezone = [GMT+ 8 ]) |
**pattern:**是你需要转换的时间日期的格式
**timezone:**是时间设置为东八区(北京时间)
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别。
再次访问控制器,会发现在浏览器中输出的json格式就会变成我们指定的时间格式了。如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15225969681","email":"123@qq测试数据","created":2018-12-19 19:00:11,"updated":"2018-12-19 19:00:11"}
加上注解后将User对象转为json字符串时也是会按照注解中的格式进行转换
二、@DateTimeFormat
Index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<%@ page language= "java" contentType= "text/html; charset=utf-8" pageEncoding= "utf-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://HdhCmsTestw3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" > <title>测试</title> </head> <body> <form method= "post" action= "/getuser" > 用户名:<input type= "text" name= "username" /></br> 密码:<input type= "password" name= "password" /></br> 手机:<input type= "text" name= "phone" /></br> 邮箱:<input type= "text" name= "email" /></br> 创建日期:<input type= "datetime" name= "created" /></br> 修改日期:<input type= "datetime" name= "updated" /></br> <input type= "submit" /> </form> </body> </html> |
1 2 3 4 5 6 7 8 |
@RequestMapping (value= "/getuser" , method=RequestMethod.POST) @ResponseBody public TbUser getuser(TbUser user) { System.out.println( "-------------------------------" ); System.out.println(user.toString()); System.out.println( "-------------------------------" ); return user; } |
当User实体类created、updated不加注解 @DateTimeFormat(pattern = [yyyy-MM-dd]) 时可以输入任意格式的日期如yyyy-MM-dd、yyyy/MM/dd…,后台仍会将接收到的字符串转换为Date,但如果加上@DateTimeFormat注解就只能按照注解后面的日期格式进行输入了。
当User实体类created、updated不加注解 @DateTimeFormat(pattern = [yyyy-MM-dd]) 时可以输入任意格式的日期如yyyy-MM-dd、yyyy/MM/dd…,后台仍会将接收到的字符串转换为Date,但如果加上@DateTimeFormat注解就只能按照注解后面的日期格式进行输入了。
1 2 3 4 5 6 |
@DateTimeFormat (pattern = "yyyy-MM-dd" ) @JsonFormat (pattern = "yyyy-MM-dd HH:mm:ss" ,timezone= "GMT+8" ) private Date created; @DateTimeFormat (pattern = "yyyy-MM-dd" ) @JsonFormat (pattern = "yyyy-MM-dd HH:mm:ss" ,timezone= "GMT+8" ) private Date updated; |
控制台输出结果如下:
User [id=null, username=test, password=123, phone=12345678901, email=12112@qq测试数据, created=Thu Dec 20 0 CST 2012, updated=Thu Dec 20 0 CST 2012]
总结:注解**@JsonFormat**:主要是控制后台到前台的时间格式
注解**@DateTimeFormat**:主要是限制前台到后台的时间格式
顺便分享一个json和Object互转的工具类,源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package com测试数据mon.utils; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtils { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 将对象转换成json字符串。 * <p>Title: pojoToJson</p> * <p>Description: </p> * @param data * @return */ public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null ; }
/** * 将json结果集转化为对象 * * @param jsonData json数据 * @param clazz 对象中的object类型 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null ; }
/** * 将json数据转换成pojo对象list * <p>Title: jsonToList</p> * <p>Description: </p> * @param jsonData * @param beanType * @return */ public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List. class , beanType); try { List<T> list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null ; } } |
Json Date日期格式化以及字段过滤
json 数据的日期格式化一直都是一个问题,没有能够按照自己想要的格式格式化的方法或者工具,所以把自己用过的整理一下.
引入jar包:
jackson-all-1.8.5.jar 不一定固定这个版本.
org.codehaus.jackson.map.ObjectMapper.class 需要导入这个转换对象.
maven依赖:版本自适配
1 2 3 4 5 |
< dependency > < groupId >com.alibaba</ groupId > < artifactId >fastjson</ artifactId > < version >1.2.15</ version > </ dependency > |
Null转空串""
1 2 3 4 5 6 7 8 9 10 11 |
// Date日期格式化 ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" )); // 将null替换为"" mapper.getSerializerProvider().setNullValueSerializer( new JsonSerializer<Object>() { @Override public void serialize(Object obj, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { jg.writeString( "" ); // Null 值转 [](String串) } }); |
实现json字段的过滤:
1 2 3 4 5 6 7 8 9 10 |
// 只保留包含的字段 // 实现自定义字段保留filterOutAllExcept,过滤serializeAllExcept mapper.setFilters( new SimpleFilterProvider().addFilter(ReportLoss. class .getName(), SimpleBeanPropertyFilter.serializeAllExcept( "id" , "title" ))); mapper.setAnnotationIntrospector( new JacksonAnnotationIntrospector(){ @Override public Object findFilterId(AnnotatedClass ag) { return ag.getName(); } }); |
格式化后的结果获取:
1 2 |
// 得到格式化后的json数据 String asString = mapper.writeValueAsString(queryActiveList); |
注解的释义:
注解使用:(对象)
字段注解过滤
@JsonIgnore属性上 或者 @JsonIgnoreProperties({"createTime","valid"})实体类上
@JsonProperty("idName")更改字段名,属性上
1 2 3 4 |
// 过滤对象的null属性. mapper.setSerializationInclusion(Inclusion.NON_NULL); // 过滤map中的null值 mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false ); |
json转map:
1 2 3 4 5 6 7 8 9 10 11 12 |
//JSONObject转Map<String, Object> @SuppressWarnings ( "unchecked" ) private Map<String, Object> getJsonToMap(JSONObject json) { Map<String,Object> map = new HashMap<String, Object>(); try { ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(json.toString(), Map. class ); } catch (Exception e) { e.printStackTrace(); } return map; } |
为了方便,整理了一份工具类:JsonDMOUtil.java
JsonDMOUtil.java (json日期格式化以及转换工具类)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * jsonDMUtil工具类 by cdw */ public class JsonDMOUtil { /** * @param object 格式化的数据 * @param dateFormate 格式化的日期格式 * @return 返回格式化后的数据 */ public static String jsonDateFormate(Object object, String dateFormate) { String asString = "" ; try { // Date日期格式化 if ( "" .equals(dateFormate.trim()) || dateFormate == null ) { dateFormate = "yyyy-MM-dd HH:mm:ss" ; } ObjectMapper mapper = JsonDMOUtil.getObjectMapper(dateFormate); // 得到格式化后的json数据 asString = mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return asString; } /** * @param object 格式化的数据 * @param dateFormate 格式化的日期格式 * @return 返回格式化后的数据 */ public static JSONObject jsonDTOFormate(Object object, String dateFormate) { String asString = "" ; try { // Date日期格式化 if ( "" .equals(dateFormate.trim()) || dateFormate == null ) { dateFormate = "yyyy-MM-dd HH:mm:ss" ; } ObjectMapper mapper = JsonDMOUtil.getObjectMapper(dateFormate); // 得到格式化后的json数据 asString = mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return JSON.parseObject(asString); } /** * @param object 格式化的数据,将JSONObject转成Map * @param dateFormate 格式化的日期格式 * @return 返回格式化后的数据 */ @SuppressWarnings ( "unchecked" ) public static Map<String, String> jsonDTMFormate(Object object, String dateFormate) { Map<String, String> resultMap = new HashMap<String, String>(); try { JSONObject jsonObj = JSON.parseObject(object.toString()); // Date日期格式化 if ( "" .equals(dateFormate.trim()) || dateFormate == null ) { dateFormate = "yyyy-MM-dd HH:mm:ss" ; } ObjectMapper mapper = JsonDMOUtil.getObjectMapper(dateFormate); JSONObject header = jsonObj.getJSONObject( "header" ); JSONObject body = jsonObj.getJSONObject( "body" ); Map<String, String> headerMap = null ; Map<String, String> bodyMap = null ; if (header != null ) { headerMap = mapper.readValue(header.toString(), Map. class ); for (Entry<String, String> map : headerMap.entrySet()) { resultMap.put(map.getKey(), map.getValue()); } } if (body != null ) { bodyMap = mapper.readValue(body.toString(), Map. class ); for (Entry<String, String> map : bodyMap.entrySet()) { resultMap.put(map.getKey(), map.getValue()); } } if (resultMap.isEmpty()) { resultMap = mapper.readValue(jsonObj.toString(), Map. class ); } } catch (Exception e) { e.printStackTrace(); } return resultMap; } /** * @param object 格式化的数据, * 默认格式化的日期格式("yyyy-MM-dd HH:mm:ss") * @return 返回格式化后的数据 */ public static String jsonDateFormate(Object object) { String asString = "" ; try { // Date日期格式化 ObjectMapper mapper = JsonDMOUtil.getObjectMapper( "yyyy-MM-dd HH:mm:ss" ); asString = mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return asString; } /** * @param object 格式化的数据, * 默认格式化的日期格式("yyyy-MM-dd HH:mm:ss") * @return 返回格式化后的数据 */ public static JSONObject jsonDTOFormate(Object object) { String asString = "" ; try { // Date日期格式化 ObjectMapper mapper = JsonDMOUtil.getObjectMapper( "yyyy-MM-dd HH:mm:ss" ); asString = mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return JSON.parseObject(asString); } /** * @param object 格式化的数据,将JSONObject转成Map, * 默认格式化的日期格式("yyyy-MM-dd HH:mm:ss") * @return 返回格式化后的数据 */ @SuppressWarnings ( "unchecked" ) public static Map<String, String> jsonDTMFormate(Object object) { Map<String, String> resultMap = new HashMap<String, String>(); try { JSONObject jsonObj = JSON.parseObject(object.toString()); // Date日期格式化 ObjectMapper mapper = JsonDMOUtil.getObjectMapper( "yyyy-MM-dd HH:mm:ss" ); JSONObject header = jsonObj.getJSONObject( "header" ); JSONObject body = jsonObj.getJSONObject( "body" ); Map<String, String> headerMap = null ; Map<String, String> bodyMap = null ; if (header != null ) { headerMap = mapper.readValue(header.toString(), Map. class ); for (Entry<String, String> map : headerMap.entrySet()) { resultMap.put(map.getKey(), map.getValue()); } } if (body != null ) { bodyMap = mapper.readValue(body.toString(), Map. class ); for (Entry<String, String> map : bodyMap.entrySet()) { resultMap.put(map.getKey(), map.getValue()); } } if (resultMap.isEmpty()) { resultMap = mapper.readValue(jsonObj.toString(), Map. class ); } } catch (Exception e) { e.printStackTrace(); } return resultMap; } /** * @param dateFormate 格式化的日期格式 * @return 返回ObjectMapper对象 */ private static ObjectMapper getObjectMapper(String dateFormate) { // Date日期格式化 ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat( new SimpleDateFormat(dateFormate)); // 将null替换为"" mapper.getSerializerProvider().setNullValueSerializer( new JsonSerializer<Object>() { @Override public void serialize(Object obj, JsonGenerator jg, SerializerProvider sp) throws IOException { jg.writeString( "" ); // Null 值转 [](String串) } }); return mapper; } } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/qq_37011759/article/details/85138707
查看更多关于使用@JsonFormat和@DateTimeFormat对Date格式化操作的详细内容...