Spring Boot整合之Fastjson
阿新 • • 發佈:2018-12-20
1.匯入依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
2.建立管理類WebConfig
@Configuration 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.建立測試實體類
public class Test_Table {
private Integer id;
private String username;
private Date birthday;
}
getter 和 setter 此處省略。
4.建立Controller
@Controller @RequestMapping("fastjson") public class FastJsonController{ @RequestMapping("/test") @ResponseBody public Test_Table test() { Test_Table test_table = new Test_Table(); test_table.setId(1); test_table.setUsername("湯姆"); test_table.setBirthday(new Date()); return test_table; } }
結果如下:
亂碼,在@RequestMapping新增
@RequestMapping(value = "/test",produces="text/html;charset=UTF-8")
日期是毫秒數,我們在 User 類中使用 Fastjson 的註解,如下內容:
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date birthday;
再次測試,結果如下:
當日期格式與我們修改的內容格式一致,說明 Fastjson 整合成功。