springboot配置Jackson返回統一默認值的實現示例

在項目開發中,我們返回的數據或者對象沒有的時候一般直接返回的null

有數據時的返回值

{
 "flag": true,
 "code": "10000",
 "msg": "成功!",
 "data": {
  "id": 32,
  "templateType": 1,
  "templateName": "我的測試模板1",
  "freightName": "我的測試標題1",
  "listArea": [
   {
    "id": 968,
    "templateId": 32,
    "freightPrice": 15,
   }
  ],
  "templateDescEntity": {
   "id": 1
   "name": "xxx"
  }
 }
}

沒有數據時的返回值

{
 "flag": true,
 "code": "10000",
 "msg": "成功!",
 "data": {
  "id": 32,
  "templateType": 1,
  "templateName": null,
  "freightName": null,
  "listArea": null,
  "templateDescEntity": null
 }
}

這種情況下數據返回給前端,前端需要做大量的空值判斷
如前端調使用屬性data.templateDescEntity.id的時候就會直接報異常
此時我們可以使用返回值統一處理,配置如下

pom.xml添加

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.5</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

java類添加配置

package com.ys.mall.core.product.config;

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.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 數據返回給前端時,設置null值默認為""
 *
 * @author cgh
 * @date 2020/12/14 10:35
 */
@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                String fieldName = jsonGenerator.getOutputContext().getCurrentName();
                try {
                    //反射獲取字段類型
                    Field field = jsonGenerator.getCurrentValue().getClass().getDeclaredField(fieldName);
                    if (CharSequence.class.isAssignableFrom(field.getType())) {
                        //字符串型空值""
                        jsonGenerator.writeString("");
                        return;
                    } else if (Collection.class.isAssignableFrom(field.getType())) {
                        //列表型空值返回[]
                        jsonGenerator.writeStartArray();
                        jsonGenerator.writeEndArray();
                        return;
                    } else if (Map.class.isAssignableFrom(field.getType())) {
                        //map型空值 或者 bean對象 返回{}
                        jsonGenerator.writeStartObject();
                        jsonGenerator.writeEndObject();
                        return;
                    }
                } catch (NoSuchFieldException ignored) {
                }

                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

添加空值統一處理後的返回值

{
 "flag": true,
 "code": "10000",
 "msg": "成功!",
 "data": {
  "id": 32,
  "templateType": 1,
  "templateName": "",
  "freightName": "",
  "listArea": [],
  "templateDescEntity": {}
 }
}

到此這篇關於springboot配置Jackson返回統一默認值的實現示例的文章就介紹到這瞭,更多相關springboot Jackson返回統一默認值內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: