springmvc fastjson deserialization time formatting method of recommends

  • 2020-06-23 00:29:20
  • OfStack

The first situation is to get the data from the background and deserialize the data. The deserialization format time: After trying many online methods, I finally found that The date field above the entity class was annotated as follows. The formatting operation could be completed; otherwise, the default format would be the timestamp format:

@JSONField (format="yyyy-MM-dd HH:mm:ss")
public Date birthday;

@JSONField (format="yyyy-MM-dd HH:mm:ss")
public Date birthday;

The second case is: response returned to the previous paragraph of the time format, 1 is the time stamp, need to be converted to the desired format yyyy-ES15en-ES16en rewrite method:


package com.jjs.util; 
 
import java.io.IOException; 
 
import org.springframework.http.HttpOutputMessage; 
import org.springframework.http.converter.HttpMessageNotWritableException; 
 
import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializerFeature; 
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 
 
public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter { 
 
  @Override 
  protected void writeInternal(Object obj, HttpOutputMessage outputMessage) 
      throws IOException, HttpMessageNotWritableException { 
    // TODO Auto-generated method stub 
    JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH"; 
    JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); 
    super.writeInternal(obj, outputMessage); 
 
  } 
 
} 

Then, change the configuration of springMVC.xml (project specific file name) to the following, serializing json by referring to the class that overrides the writeInternal() method


<mvc:annotation-driven> 
    <mvc:message-converters register-defaults="true"> 
      <!-- <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> --> 
      <bean class="com.jjs.util.JsonHttpMessageConverter"> 
        <property name="supportedMediaTypes"> 
          <list> 
            <value>text/html;charset=UTF-8</value> 
            <value>application/json</value> 
          </list> 
        </property> 
        <property name="features"> 
          <list> 
          <value>WriteDateUseDateFormat</value> 
            <value>WriteMapNullValue</value> 
            <value>QuoteFieldNames</value> 
          </list> 
        </property> 
      </bean> 
    </mvc:message-converters> 
  </mvc:annotation-driven> 

Record 1, easy to view


Related articles: