Spring Boot 整合之Fastjson
阿新 • • 發佈:2018-11-12
Spring Boot 整合Fastjson
1. 在pom.xml中匯入Fastjson依賴
<!--使用json物件-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
2. 建立管理類WebConfig
package com.wyp.util; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; public class WebConfig { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); } }
3. 建立實體類和資料庫表,這裡自己寫
4. 建立Controller
package com.wyp.controller; import com.wyp.pojo.TTest; import com.wyp.service.TTestService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; /** * Spring Boot整合fastjson */ @Controller @RequestMapping("fastjson") public class TTestController2 { @Resource private TTestService tTestService; @ResponseBody @RequestMapping(value = "/fastjson") public TTest test(){ TTest tTest = tTestService.getTTestListById(2); System.out.println(tTest); return tTest; } }
5. 執行SpringbootLpplication,結果如下
注:如果有亂碼問題,在Controller的方法中如下加上produces
@RequestMapping(value = "/test",produces="text/html;charset=UTF-8")
我這裡地址路徑之所以有個springboot,是因為我在application.properties中加了一個地址,如下,如果不加的話就可以去掉訪問地址中的springboot
server.servlet.context-path=/springboot