SpringBoot之控制器的返回值處理方式
SpringBoot控制器的返回值處理
@Controller
:默認(rèn)返回值是視圖名稱,如果需要返回Json字符串,需要在方法上加@ResponseBody注解,默認(rèn)使用 Jackson 框架處理。@RestController
:是@ResponseBody和@Controller的組合注解。
Spring Boot 中默認(rèn)使用的 Json 解析框架是 Jackson 。
在實(shí)際項(xiàng)目中,難免會(huì)遇到一些 null 值出現(xiàn),在轉(zhuǎn) Json 時(shí),是不希望有這些 null 出現(xiàn)的。
比如期望所有的 null 在轉(zhuǎn) Json 時(shí)都變成 “” 這種空字符串。
在 Spring Boot 中,做一下配置即可,新建一個(gè) 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中加了個(gè)屬性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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)微信公眾號(hào)自定義菜單的創(chuàng)建方法示例
這篇文章主要介紹了Java實(shí)現(xiàn)微信公眾號(hào)自定義菜單的創(chuàng)建方法,結(jié)合實(shí)例形式分析了java創(chuàng)建微信公眾號(hào)自定義菜單的具體步驟、實(shí)現(xiàn)方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-10-10詳解在Spring中如何自動(dòng)創(chuàng)建代理
這篇文章主要介紹了詳解在Spring中如何自動(dòng)創(chuàng)建代理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07Java生成動(dòng)態(tài)版驗(yàn)證碼的方法實(shí)例
這篇文章主要給大家介紹了利用Java生成動(dòng)態(tài)版驗(yàn)證碼的方法實(shí)例,本文生成的是GIF格式 + 干擾元素,讓驗(yàn)證碼破解難度又上了一個(gè)層次,文中給出了詳細(xì)的示例代碼,并在文末給出了完整的實(shí)例代碼供大家下載學(xué)習(xí),需要的朋友們下面來一起看看吧。2017-04-04JavaAgent實(shí)現(xiàn)http接口發(fā)布方式淺析
這篇文章主要介紹了JavaAgent實(shí)現(xiàn)http接口發(fā)布方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03SpringBoot整合Echarts實(shí)現(xiàn)用戶人數(shù)和性別展示功能(詳細(xì)步驟)
這篇文章主要介紹了SpringBoot整合Echarts實(shí)現(xiàn)用戶人數(shù)和性別展示,通過數(shù)據(jù)庫(kù)設(shè)計(jì)、實(shí)現(xiàn)數(shù)據(jù)訪問層、業(yè)務(wù)邏輯層和控制層的代碼編寫,以及前端頁(yè)面的開發(fā),本文詳細(xì)地介紹了SpringBoot整合Echarts的實(shí)現(xiàn)步驟和代碼,需要的朋友可以參考下2023-05-05