SpringMVC序列化Long轉成String


問題:由於JS中Number的精度為16位(最大位17位,第17位精度不准),我們的ID用的Number 18位,傳到客戶端會丟失最后兩位;
解決方式:Long序列化成String,傳到客戶端;
注意:客戶端取到的Long對應類型是String,做判斷或者計算時要注意;

springmvc.xml

  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
  <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="objectMapper" ref="customObjectMapper"/>
    <property name="supportedMediaTypes">
      <list>
        <value>application/json;charset=UTF-8</value>
        <value>text/html;charset=UTF-8</value>
      </list>
    </property>
  </bean>
  <bean id="customObjectMapper" class="com.nankang.cati.nweb.filter.CustomObjectMapper"/>
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        super();
        // 設置日期轉換yyyy-MM-dd HH:mm:ss
        setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 序列換成json時,將所有的long變成string,因為js中得數字類型不能包含所有的java long值
        SimpleModule simpleModule = new SimpleModule("LongModule", new Version(1, 0, 0, ""));
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        registerModule(simpleModule);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM