SpringBoot之控制器的返回值處理方式
SpringBoot控制器的返回值處理
@Controller:默認返回值是視圖名稱,如果需要返回Json字符串,需要在方法上加@ResponseBody注解,默認使用 Jackson 框架處理。@RestController:是@ResponseBody和@Controller的組合注解。
Spring Boot 中默認使用的 Json 解析框架是 Jackson 。
在實際項目中,難免會遇到一些 null 值出現(xiàn),在轉(zhuǎn) Json 時,是不希望有這些 null 出現(xiàn)的。
比如期望所有的 null 在轉(zhuǎn) Json 時都變成 “” 這種空字符串。
在 Spring Boot 中,做一下配置即可,新建一個 Jackson 的配置類:
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;
@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 {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
}SpringBoot 啟用Fastjson轉(zhuǎn)換
fastJson依賴導(dǎo)入:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>SpringBoot 啟用Fastjson轉(zhuǎn)換,需要繼承WebMvcConfigurerAdapter,并重寫configureMessageConverters方法。
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FastJWebMvcConfigurer extends WebMvcConfigurationSupport {
/***
* 使用阿里 FastJson 作為JSON MessageConverter
* @param converters
* */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
// 保留map空的字段
SerializerFeature.WriteMapNullValue,
// 將String類型的null轉(zhuǎn)成""
SerializerFeature.WriteNullStringAsEmpty,
// 將Number類型的null轉(zhuǎn)成0
SerializerFeature.WriteNullNumberAsZero,
// 將List類型的null轉(zhuǎn)成[]
SerializerFeature.WriteNullListAsEmpty,
// 將Boolean類型的null轉(zhuǎn)成false
SerializerFeature.WriteNullBooleanAsFalse,
// 避免循環(huán)引用
SerializerFeature.DisableCircularReferenceDetect);
// converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
List<MediaType> mediaTypeList = new ArrayList<>();
// 解決中文亂碼問題,相當(dāng)于在Controller上的@RequestMapping中加了個屬性produces = "application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
converters.add(converter);
}
}SpringBoot控制器返回值-中文亂碼問題
@RequestMapping 注解增加produces屬性解決中文亂碼問題
@RequestMapping(value="/create/index",produces = "application/json;charset=utf-8")
public ResponseBean createIndex(@RequestParam String indexName)
{
try {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("properties")
.startObject()
.field("name").startObject().field("index", "true").field("type", "keyword").endObject()
.field("age").startObject().field("index", "true").field("type", "integer").endObject()
.field("money").startObject().field("index", "true").field("type", "double").endObject()
.field("address").startObject().field("index", "true").field("type", "text").endObject()
.field("birthday").startObject().field("index", "true").field("type", "date").endObject()
//.field("address").startObject().field("index", "true").field("type", "text").field("analyzer", "ik_max_word").endObject()
//.field("birthday").startObject().field("index", "true").field("type", "date").field("format", "strict_date_optional_time||epoch_millis").endObject()
.endObject()
.endObject();
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.mapping(indexName,builder);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
if (acknowledged) {
return new ResponseBean(200, "創(chuàng)建成功", null);
} else {
return new ResponseBean(1002, "創(chuàng)建失敗", null);
}
} catch (IOException e) {
e.printStackTrace();
}catch (ElasticsearchStatusException e)
{
logger.info("創(chuàng)建失敗---索引已經(jīng)存在");
return new ResponseBean(1002, "創(chuàng)建失敗---索引已經(jīng)存在", null);
}
return null;
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實現(xiàn)微信公眾號自定義菜單的創(chuàng)建方法示例
這篇文章主要介紹了Java實現(xiàn)微信公眾號自定義菜單的創(chuàng)建方法,結(jié)合實例形式分析了java創(chuàng)建微信公眾號自定義菜單的具體步驟、實現(xiàn)方法及相關(guān)操作注意事項,需要的朋友可以參考下2019-10-10
JavaAgent實現(xiàn)http接口發(fā)布方式淺析
這篇文章主要介紹了JavaAgent實現(xiàn)http接口發(fā)布方式,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03
SpringBoot整合Echarts實現(xiàn)用戶人數(shù)和性別展示功能(詳細步驟)
這篇文章主要介紹了SpringBoot整合Echarts實現(xiàn)用戶人數(shù)和性別展示,通過數(shù)據(jù)庫設(shè)計、實現(xiàn)數(shù)據(jù)訪問層、業(yè)務(wù)邏輯層和控制層的代碼編寫,以及前端頁面的開發(fā),本文詳細地介紹了SpringBoot整合Echarts的實現(xiàn)步驟和代碼,需要的朋友可以參考下2023-05-05

