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)文章
關(guān)于String轉(zhuǎn)Json的幾種方式
這篇文章主要介紹了關(guān)于String轉(zhuǎn)Json的幾種方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
ThreadPoolExecutor參數(shù)含義及源碼執(zhí)行流程詳解
這篇文章主要為大家介紹了ThreadPoolExecutor參數(shù)含義及源碼執(zhí)行流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
JavaWeb開發(fā)入門第二篇Tomcat服務(wù)器配置講解
JavaWeb開發(fā)入門第二篇主要介紹了Tomcat服務(wù)器配置的方法教大家如何使用Tomcat服務(wù)器,感興趣的小伙伴們可以參考一下2016-04-04
java file.renameTo返回false的原因及解決方案
這篇文章主要介紹了java file.renameTo返回false的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

