spring中使用@ResponseBody註解返回json,Long類型精度丟失

原文鏈接:https://my.oschina.net/u/2555967/blog/2963920

1.現象

發現一個奇怪的bug。

對於Long 類型的數據,如果我們在Controller層通過@ResponseBody將返回數據自動轉換成json時,不做任何處理,而直接傳給前端的話,在Long長度大於17位時會出現精度丟失的問題。

2、簡單分析

@responseBody 註解的作用是將controller的方法返回的對象通過適當的轉換器(默認使用MappingJackson2HttpMessageConverte 轉換爲指定的格式之後,寫入到response對象的body區,需要注意的是,在使用此註解之後不會再走試圖處理器,而是直接將數據寫入到輸入流中,他的效果等同於通過response對象輸出指定格式的數據,作用等同於 response.getWriter.write(JSONObject.fromObject(user).toString());

3、怎麼處理

總的來說主要有兩種處理方式,最常用的辦法就是待轉化的字段統一轉成String類型

一般有兩種方式:首先我們要在maven中添加必須的依賴

  <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>版本號</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>版本號</version>
        </dependency>

方式一.

在待轉化的字段之上加上@JsonSerialize(using=ToStringSerializer.class)註解,如圖所示:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ProductVo {

    @JsonSerialize(using=ToStringSerializer.class)
    private Long productId

    private String productName;
    get,set省略

方式二.

在webconfig配置中加入自定義配置消息轉換器configureMessageConverters

@Component
class WebConfigurer extends WebMvcConfigurationSupport {
    /**
     * 序列換成json時,將所有的long變成string
     * 因爲js中得數字類型不能包含所有的java long值
     */
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章