1. 程式人生 > 實用技巧 >spring框架返回json資料null轉空字串

spring框架返回json資料null轉空字串

spring專案中,前端獲取伺服器返回的json時,裡面有null值,如果沒做校驗,就會導致js報錯,但是不推薦每個返回的地方手動處理,而是應該在框架中統一配置。

前面關於json日期格式化的文章中,提到了spring預設使用的是jackson來做json序列化,相對應的converter是MappingJackson2HttpMessageConverter,我們依舊還是要利用它提供的ObjectMapper來解決上面的問題。

方法一:

1、繼承ObjectMapper,自定義mapper

package com.ssm.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException;
import java.text.SimpleDateFormat; /** * SpringMVC中@ResponseBody返回json時,預設使用jackson,但是不會自動將null轉成空字串, * 所以這裡繼承ObjectMapper重寫構造方法,在構造方法中進行手動處理 * Created by SongFei on 2016/12/26. */ public class JsonMapper extends ObjectMapper { public JsonMapper() { super(); // null值轉空字串 this
.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeString(""); } }); // 不返回時間戳格式 this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // 遇到不認識的欄位,不拋異常 this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 指定自己想要的日期格式,如:yyyy-MM-dd HH:mm:ss this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); } }

2、在配置檔案中的<mvc:annotation-driven/>標籤中對messageconverter做特殊處理,引入自定義的ObjectMapper

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/json;charset=UTF-8</value>
                </list>
            </property>
            <!--引入自定義的ObjectMapper-->
            <property name="objectMapper">
                <bean class="com.ssm.common.JsonMapper"/>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

上述兩個步驟確認無誤之後,應該瀏覽器返回就會把null轉為"", (但是經過測試,如果在控制檯列印,還會是null,因為還沒有執行到view層呢!)

方法二:

1、將介面返回的欄位為null的設定為空字串:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.io.IOException;
 
@Configuration
public class CustomConfig {
 
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object paramT, JsonGenerator paramJsonGenerator,
                                  SerializerProvider paramSerializerProvider) throws IOException {
                //設定返回null轉為 空字串""
                paramJsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
 
}

2、設定null欄位不返回給前端:

//1.實體上
 
@JsonInclude(Include.NON_NULL) 
 
//將該標記放在屬性上,如果該屬性為NULL則不參與序列化 
//如果放在類上邊,那對這個類的全部屬性起作用 
//Include.Include.ALWAYS 預設 
//Include.NON_DEFAULT 屬性為預設值不序列化 
//Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 
//Include.NON_NULL 屬性為NULL 不序列化 
 
//2.程式碼上
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);  
 
//通過該方法對mapper物件進行設定,所有序列化的物件都將按改規則進行系列化 
//Include.Include.ALWAYS 預設 
//Include.NON_DEFAULT 屬性為預設值不序列化 
//Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 
//Include.NON_NULL 屬性為NULL 不序列化

如果是springboot專案,就更簡單了,直接在config類中對ObjectMapper操作,都不用自己重新寫:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    List<MediaType> supported = new ArrayList<>();
    supported.add(MediaType.APPLICATION_JSON_UTF8);
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(supported);

    // JsonMapper
    ObjectMapper objectMapper = new ObjectMapper();

    // null值的處理,必須要放在第一步,否則會將下面的日期格式化覆蓋掉
    // null ==> ""
    objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString("");
        }
    });

    // 處理預設日期格式化:yyyy-MM-dd HH:mm:ss
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setDateFormat(new SimpleDateFormat(Constants.TIME_PATTERN));
    
    mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
    return mappingJackson2HttpMessageConverter;
}

轉 :https://www.jiweichengzhu.com/article/225600001e034f2691345ac14673b108

轉:https://blog.csdn.net/qq_40741855/article/details/106095808