In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is the Json conversion of SpringMVC @ RequestBody Date". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the Json conversion of SpringMVC @ RequestBody Date"?
Catalogue
Json conversion of SpringMVC @ RequestBody Date type
Format DateFormat through GsonBuilder
Take the zero configuration framework as an example
Take the code implementation under the framework of zero configuration as an example.
@ RequestBody receives the json string and automatically converts the date string to java.util.Date
1. Configure springMVC to receive json strings
2.@Controller class code
3. Entity class object code
4.DateJsonSerializer class code
5.DateJsonDeserializer class code
Json conversion of SpringMVC @ RequestBody Date type
When you normally use Json or Gson to serialize the Date type into a string, you get a string in the form of "Dec 5, 2017 8:03:34 PM". It is difficult to understand when this is in this format at the front end, and the readability is very low.
At the same time, if you use this form of string to deserialize into a Date object, it will also fail, and the process is irreversible. How to serialize a Date object into a string of specified format, such as a string of "yyyy-MM-dd" format, is illustrated by the use of Gson.
For Gson objects, you can use GsonBuilder to instantiate
Set the format of DateFormat through GsonBuilder Gson gson = new GsonBuilder () .setDateFormat ("yyyy-MM-dd HH:mm:ss") .create ()
After this setting, when the Date object is serialized using the toJson (Object obj) method, a string in the format "yyyy-MM-dd HH:mm:ss" is output
You can also deserialize a string in the format "yyyy-MM-dd HH:mm:ss" into a Date object. It is worth noting that when a Date object does not specify "HH:mm:ss", it is populated with the current time to complete the format length.
The above is about the serialization and deserialization of Date objects into strings, which is not applicable in the SpingMVC framework. Let's talk about the serialization and deserialization of Date in SpringMVC.
In SpringMVC, if the front end passes a string in the form of GET, and the back end wants to deserialize the string into a Date object, the most common thing is to register the Formatter object
Take the zero configuration framework as an example: public class String2DateFormatter implements Formatter {private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String DATE_FORMAT = "yyyy-MM-dd"; @ Override public String print (Date object, Locale locale) {return new GsonBuilder () .setDateFormat (DATE_TIME_FORMAT) .create () .toJson (object) } @ Override public Date parse (String text, Locale locale) throws ParseException {if (text.length () > 10) {return new SimpleDateFormat (DATE_TIME_FORMAT) .parse (text);} else {return new SimpleDateFormat (DATE_FORMAT) .parse (text);} public class MvcContextConfig extends WebMvcConfigurerAdapter {. Override public void addFormatters (FormatterRegistry registry) {registry.addFormatter (new String2DateFormatter ());}.}
Of course, you can also use the form of configuration file configuration, the specific method, please Baidu.
The current side passes a string, and when Controller accepts it with a parameter of type Date, it uses Formatter to deserialize the string into a Date object.
If the front end passes a Json object in the form of POST, there is a Date property inside the object, the front end passes a string, and the back end receives it with a compound object that identifies @ RequestBody, Formatter will not work.
What works at this point is the implementation class of HttpMessageConverter. Normally, there are Jackson or Gson dependencies within the project, which can deserialize Json into composite objects.
If you rely on Jackson and use Jackson's HttpMessageConverter to deserialize Json, you can only deserialize properties of simple data types, not Date types; but if you are of Gson type, you can deserialize in "yyyy-MM-dd HH:mm:ss" format, and the "yyyy-MM-dd" format is not supported, and other formats are uncertain.
That is to say, depending on Gson, the front-end "yyyy-MM-dd HH:mm:ss" format string can be deserialized into a Date object, but when the Date object is returned to the front end, the parsed string is still in the form of "Dec 5, 2017 8:03:34 PM", which is not desirable.
When we use Jackson as the parser for serialization and deserialization of Json objects
Take the code implementation under the zero configuration framework as an example to explain public class MvcContextConfig extends WebMvcConfigurerAdapter {. @ Override public void configureMessageConverters (List application/json;charset=UTF-8 2.@Controller class code @ RequestMapping (value= "/ addDicAppUsers.do") @ ResponseBody public boolean addDicAppUsers (@ RequestBody DicAppUsersModel dicAppUsersModel) {if (dicAppUsersService.addDicAppUsers (dicAppUsersModel)) {return true;} else {return false;} 3. Entity class object code package com.mvc.model; import java.util.Date;import org.codehaus.jackson.map.annotate.JsonDeserialize;import org.codehaus.jackson.map.annotate.JsonSerialize;import com.mvc.imp.DateJsonDeserializer;import com.mvc.imp.DateJsonSerializer; / * user view class * @ author suyunlong * * / @ SuppressWarnings ("serial") public class DicAppUsersModel implements java.io.Serializable {private long id; private String loginid; private String loginname; private String loginpassword; private String loginunitcode; private String workplace @ JsonSerialize (using=DateJsonSerializer.class) @ JsonDeserialize (using=DateJsonDeserializer.class) private Date addtime; private long sourceid; @ JsonSerialize (using=DateJsonSerializer.class) @ JsonDeserialize (using=DateJsonDeserializer.class) private Date createdate; public DicAppUsersModel () {super ();} public DicAppUsersModel (long id, String loginid, String loginname, String loginpassword, String loginunitcode, String workplace, Date addtime, long sourceid, Date createdate) {super (); this.id = id; this.loginid = loginid; this.loginname = loginname; this.loginpassword = loginpassword; this.loginunitcode = loginunitcode This.workplace = workplace; this.addtime = addtime; this.sourceid = sourceid; this.createdate = createdate;} public long getId () {return id;} public void setId (long id) {this.id = id;} public String getLoginid () {return loginid;} public void setLoginid (String loginid) {this.loginid = loginid;} public String getLoginname () {return loginname;} public void setLoginname (String loginname) {this.loginname = loginname } public String getLoginpassword () {return loginpassword;} public void setLoginpassword (String loginpassword) {this.loginpassword = loginpassword;} public String getLoginunitcode () {return loginunitcode;} public void setLoginunitcode (String loginunitcode) {this.loginunitcode = loginunitcode;} public String getWorkplace () {return workplace;} public void setWorkplace (String workplace) {this.workplace = workplace;} public Date getAddtime () {return addtime;} public void setAddtime (Date addtime) {this.addtime = addtime } public long getSourceid () {return sourceid;} public void setSourceid (long sourceid) {this.sourceid = sourceid;} public Date getCreatedate () {return createdate;} public void setCreatedate (Date createdate) {this.createdate = createdate;}} 4.DateJsonSerializer class code package com.mvc.imp; import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import org.codehaus.jackson.JsonGenerator;import org.codehaus.jackson.JsonProcessingException;import org.codehaus.jackson.map.JsonSerializer Import org.codehaus.jackson.map.SerializerProvider; public class DateJsonSerializer extends JsonSerializer {public static final SimpleDateFormat format=new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); public void serialize (Date date,JsonGenerator jsonGenerator,SerializerProvider serializerProvider) throws IOException,JsonProcessingException {jsonGenerator.writeString (format.format (date));} 5.DateJsonDeserializer class code package com.mvc.imp; import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import org.codehaus.jackson.JsonParser;import org.codehaus.jackson.JsonProcessingException Import org.codehaus.jackson.map.DeserializationContext;import org.codehaus.jackson.map.JsonDeserializer; public class DateJsonDeserializer extends JsonDeserializer {public static final SimpleDateFormat format=new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); public Date deserialize (JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException,JsonProcessingException {try {return format.parse (jsonParser.getText ());} catch (Exception e) {System.out.println (e.getMessage ()); throw new RuntimeException (e);}
In this way, the received json date string can be converted to Date. Later, you can save the date data directly through the Date type.
Thank you for your reading, the above is the content of "what is the Json conversion of SpringMVC @ RequestBody Date type". After the study of this article, I believe you have a deeper understanding of what the Json conversion of SpringMVC @ RequestBody Date type is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.