小编给大家分享一下如何使用@JSONFORMat和@DateTimeFormat对Date格式化操作,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!@jsonFor
小编给大家分享一下如何使用@JSONFORMat和@DateTimeFormat对Date格式化操作,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
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;} }
控制器:
@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.com"); user.setUpdated(new Date()); user.setCreated(new Date()); return user; }
访问控制器在浏览器中输出的json格式如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15212559252","email":"123@qq.com","created":1545288773904,"updated":"1545288773904"}
可见created、updated这两个属性值是时间戳并不是“yyyy-MM-dd HH:mm:ss”格式,那怎么把日期类型格式化成我们想要的类型呢,其实很简单只需要在实体类的属性上加上**@JsonFormat**注解就行了。
@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;
@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)
**pattern:**是你需要转换的时间日期的格式
**timezone:**是时间设置为东八区(北京时间)
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别。
再次访问控制器,会发现在浏览器中输出的json格式就会变成我们指定的时间格式了。如下:
{"id":1001,"username":"zhangsan","password":"1234567","phone":"15225969681","email":"123@qq.com","created":2018-12-19 19:00:11,"updated":"2018-12-19 19:00:11"}
加上注解后将User对象转为json字符串时也是会按照注解中的格式进行转换
Index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "Http://www.w3.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>
@RequestMapping(value="/getuser", method=RequestMethod.POST)@ResponseBodypublic 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注解就只能按照注解后面的日期格式进行输入了。
@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.com, created=Thu Dec 20 00:00:00 CST 2012, updated=Thu Dec 20 00:00:00 CST 2012]
注解**@JsonFormat**:主要是控制后台到前台的时间格式
注解**@DateTimeFormat**:主要是限制前台到后台的时间格式
package com.common.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(); public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } 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; } 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 数据的日期格式化一直都是一个问题,没有能够按照自己想要的格式格式化的方法或者工具,所以把自己用过的整理一下.
引入jar包:
jackson-all-1.8.5.jar 不一定固定这个版本.
org.codehaus.jackson.map.ObjectMapper.class 需要导入这个转换对象.
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version></dependency>
// 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串) }});
// 只保留包含的字段// 实现自定义字段保留filterOutAllExcept,过滤serializeAllExceptmapper.setFilters(new SimpleFilterProvider().addFilter(ReportLoss.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept("id", "title")));mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector(){ @Override public Object findFilterId(AnnotatedClass ag) { return ag.getName(); }});
// 得到格式化后的json数据String asString = mapper.writeValueAsString(queryActiveList);
注解使用:(对象)
字段注解过滤
@JsonIgnore属性上 或者 @JsonIgnoreProperties({"createTime","valid"})实体类上
@JsonProperty("idName")更改字段名,属性上
// 过滤对象的null属性.mapper.setSerializationInclusion(Inclusion.NON_NULL);// 过滤map中的null值mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
//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
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;public class JsonDMOUtil { 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; } 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); } @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; } 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; } 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); } @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; } 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; }}
以上是“如何使用@JsonFormat和@DateTimeFormat对Date格式化操作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!
--结束END--
本文标题: 如何使用@JsonFormat和@DateTimeFormat对Date格式化操作
本文链接: https://lsjlt.com/news/300130.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0