在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java/ Spring MVC 中如何自定義 Gson 的消息轉(zhuǎn)換器?

Spring MVC 中如何自定義 Gson 的消息轉(zhuǎn)換器?

Spring MVC 中通過(guò)配置 Gson 的消息轉(zhuǎn)換器可以使 Controller 層直接返回對(duì)象而非手動(dòng)去轉(zhuǎn)換對(duì)象為 json 字符串之后再返回。

  <mvc:annotation-driven>
    <mvc:message-converters>
      <!--避免返回String亂碼-->
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
          <list>
            <value>text/plain;charset=UTF-8</value>
            <value>text/html;charset=UTF-8</value>
          </list>
        </property>
      </bean>
      <!--Json轉(zhuǎn)換,property 避免 Ie 執(zhí)行 Ajax 時(shí),返回 Json 出現(xiàn)下載文件-->
      <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter">
        <property name="supportedMediaTypes">
          <list>
            <value>text/plain;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
          </list>
        </property>
        <!--輸出json結(jié)果格式化-->
        <property name="gson">
          <bean class="org.springframework.http.converter.json.GsonFactoryBean">
            <!--輸出null,false則不輸出null值
            <property name="serializeNulls" value="true" />-->
            <!--不對(duì)html標(biāo)簽轉(zhuǎn)碼,false會(huì)導(dǎo)致所有html標(biāo)簽轉(zhuǎn)碼為 \ue300 格式-->
            <property name="disableHtmlEscaping" value="true"/>
            <!--格式化日期-->
            <property name="dateFormatPattern" value="yyyy-MM-dd HH:mm:ss"/>
          </bean>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

Java 中的代碼也很簡(jiǎn)潔,類(lèi)似于下面那的代碼:

  @RequestMapping(path = "/getUserInfoPageByParam")
  @ResponseBody
  public JsonResult<UserInfo> getUserInfoPageByParam() {
    //獲取數(shù)據(jù)并直接返回,由 GsonHttpMessageConverter 在后臺(tái)進(jìn)行轉(zhuǎn)換包裝成 json 字符串
    return jsonResult;
  }

但是 Gson 默認(rèn)的轉(zhuǎn)換會(huì)把 Java 中的 long/Long 類(lèi)型的數(shù)據(jù)轉(zhuǎn)換為 JavaScript 中的 Number 類(lèi)型,這看起來(lái)沒(méi)什么問(wèn)題的轉(zhuǎn)換卻會(huì)造成一個(gè)麻煩,就是 JavaJavaScript 的數(shù)值類(lèi)型最大值不同。JavaLong 最大值在 JavaScript 會(huì)出現(xiàn)溢出的行為,然后就造成了大整數(shù)精度丟失。
例如 396193654462615552 到 JavaScript 中之后會(huì)變成 396193654462615550,現(xiàn)在吾輩只能手動(dòng)轉(zhuǎn)換對(duì)象,將 Long 都包裝成字符串類(lèi)型然后傳到頁(yè)面,Controller 里面是類(lèi)似于下面的代碼:

  @RequestMapping(path = "/getUserInfoPageByParam")
  @ResponseBody
  public String getUserInfoPageByParam() {
    //獲取數(shù)據(jù)并存到 jsonResult 中
    return GsonUtil.gsonToString(jsonResult);
  }

現(xiàn)在這樣暫時(shí)能用,但這樣的代碼太丑了點(diǎn),有沒(méi)有什么辦法能夠做到類(lèi)似于第一種直接返回對(duì)象不用手動(dòng)轉(zhuǎn)換的方法呢?(前提是把 Long 的大數(shù)字溢出解決掉呀)

回答
編輯回答
別傷我

問(wèn)題前幾天通過(guò)一個(gè)方法解決掉了,不過(guò)今天才來(lái)的及補(bǔ)充一下解決問(wèn)題的方法。

其實(shí)也就是將默認(rèn)使用的 GsonHttpMessageConverter 消息轉(zhuǎn)換器給替換掉了
spring-web.xml 里面的相關(guān)配置如下:

 <!--消息轉(zhuǎn)換器 輸出對(duì)象轉(zhuǎn)JSON支持-->
  <mvc:annotation-driven>
    <mvc:message-converters>
      <!--避免返回String亂碼-->
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
          <list>
            <value>text/plain;charset=UTF-8</value>
            <value>text/html;charset=UTF-8</value>
          </list>
        </property>
      </bean>
      <!--Json轉(zhuǎn)換,property 避免 Ie 執(zhí)行 Ajax 時(shí),返回 Json 出現(xiàn)下載文件-->
      <!--<bean class="org.springframework.http.converter.json.GsonHttpMessageConverter">-->
      <!--這兒是重點(diǎn),吾輩將默認(rèn)使用的 GsonHttpMessageConverter 替換成了吾輩自己的 GsonMessageConfig 類(lèi)-->
      <bean class="com.interview.conf.GsonMessageConfig">
        <property name="supportedMediaTypes">
          <list>
            <value>text/plain;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
          </list>
        </property>
        <!--輸出json結(jié)果格式化-->
        <property name="gson">
          <bean class="org.springframework.http.converter.json.GsonFactoryBean">
            <!--輸出null,false則不輸出null值
            <property name="serializeNulls" value="true" />-->
            <!--不對(duì)html標(biāo)簽轉(zhuǎn)碼,false會(huì)導(dǎo)致所有html標(biāo)簽轉(zhuǎn)碼為 \ue300 格式-->
            <property name="disableHtmlEscaping" value="true"/>
            <!--格式化日期-->
            <property name="dateFormatPattern" value="yyyy-MM-dd HH:mm:ss"/>
          </bean>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

下面是 GsonMessageConfig 的代碼:

package com.interview.conf;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;

/**
 * Gson 轉(zhuǎn)換時(shí)的一些問(wèn)題,手動(dòng)配置一下轉(zhuǎn)換的對(duì)象.
 *
 * @author rxliuli
 */
@Configuration
public class GsonMessageConfig extends GsonHttpMessageConverter {
  /**
   * 項(xiàng)目中轉(zhuǎn)換 json 默認(rèn)使用的 Gson 對(duì)象.
   */
  private static final Gson DEFAULT_GSON = new GsonBuilder()
    //null 也序列化
    .serializeNulls()
    //時(shí)間轉(zhuǎn)化為特定格式 yyyy-MM-dd HH:mm:ss
    .setDateFormat("yyyy-MM-dd hh:mm:ss")
    //設(shè)置 Long 類(lèi)型自動(dòng)轉(zhuǎn)換成 String 類(lèi)型
    .setLongSerializationPolicy(LongSerializationPolicy.STRING)
    //執(zhí)行創(chuàng)建 Gson 轉(zhuǎn)換對(duì)象
    .create();

  @Override
  public void setGson(Gson gson) {
    super.setGson(
      DEFAULT_GSON
    );
  }
}

這樣,吾輩 web 層的代碼全部都不必進(jìn)行任何修改,在頁(yè)面中取值時(shí)所有的 Long 類(lèi)型的字段都會(huì)被轉(zhuǎn)換成 String 字符串類(lèi)型,不用再擔(dān)心 Java 中的 Long 類(lèi)型的字段到 js 時(shí)發(fā)生大數(shù)字溢出了?。ú贿^(guò)講道理吾輩總覺(jué)得有更好的解決方案來(lái)著,這種方式略微有些不太優(yōu)雅。。。(′???`))

2017年12月18日 19:25
編輯回答
陌顏

<mvc:annotation-driven/> 默認(rèn)就提供了:數(shù)據(jù)綁定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,讀寫(xiě)XML的支持(JAXB,讀寫(xiě)JSON的支持(Jackson)。我們處理響應(yīng)ajax請(qǐng)求時(shí),就使用到了對(duì)json的支持(配置之后,在加入了jackson的core和mapper包之后,不寫(xiě)配置文件也能自動(dòng)轉(zhuǎn)換成json)。
你配置Gson,使 Controller 層直接返回對(duì)象而非手動(dòng)去轉(zhuǎn)換對(duì)象為 json 字符串之后再返回的做法其實(shí)算是多此一舉。

直接這樣配置就夠了:

<mvc:annotation-driven/>
2018年5月11日 09:55
編輯回答
空白格

Gson支持自定義類(lèi)型轉(zhuǎn)換

GsonBuilder builder=new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd kk:mm:ss");
builder.registerTypeAdapter(Long.class, new Test1());
gson=builder.create(); 

class Test1 extends TypeAdapter<Long>{

    @Override
    public Long read(JsonReader arg0) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void write(JsonWriter arg0, Long arg1) throws IOException {
        // TODO Auto-generated method stub
        
    }
}
2017年5月26日 06:53
編輯回答
深記你

直接用注解

@RestController
public class HelloWorldController {

    @RequestMapping("/hello")
    public Test test() {
        Test test =  new Test();
        test.setId(1);
        test.setName("哈哈哈")
        return test;
    }

} 

這樣的返回就是 json

2017年5月9日 21:23