天天看點

十一,SpringBoot-使用FastJson解析Json資料

 springboot預設使用的是Jackson。接下來講下如何在springboot項目中使用fastjson。

========以下項目為示例======

說一句廢話:這裡application用的properties類型的。重點是方法,yml檔案中同樣适用,不同的隻是語言格式而已

①,使用fastjson需要引入依賴

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.15</version>

</dependency>

十一,SpringBoot-使用FastJson解析Json資料

②,在項目啟動類中繼承WebMvcConfigurerAdapter,并重寫configureMessageConverters

public class WebDevApplication extends WebMvcConfigurerAdapter {


    //重寫fastJson消息轉換器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //建立fastJson消息轉換器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //建立配置對象
        FastJsonConfig config = new FastJsonConfig();
        //對json資料進行格式化
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        converter.setFastJsonConfig(config);
        converters.add(converter);
    }

    public static void main(String[] args)      
十一,SpringBoot-使用FastJson解析Json資料

③,建立一個實體類PersionModel。

package webdev.model;

import java.util.Date;

public class PersonModel {
    private String name;
    private String nickName;
    private Date birthday;

    //geter setter 省略。。。      
十一,SpringBoot-使用FastJson解析Json資料

④,Controller中寫一個方法調用

@RestController
public class WcbDevController {

    @RequestMapping("/getPerInfo")
    public Object getPerInfo(){
        PersonModel personModel = new PersonModel();
        personModel.setBirthday(new Date());
        personModel.setNickName("不要噴香水");
        return      
十一,SpringBoot-使用FastJson解析Json資料

⑤,啟動項目通路

十一,SpringBoot-使用FastJson解析Json資料
十一,SpringBoot-使用FastJson解析Json資料

編輯

我們發現日期是毫秒數,姓名出現了亂碼。我們知道springboot預設使用的編碼是UTF-8,但是這裡還是出現了亂碼。

解決亂碼:在application添加以下配置即可:

spring.http.encoding.force=true
十一,SpringBoot-使用FastJson解析Json資料

作用是開啟springboot對response相應的編碼設定。

⑥,重新通路

十一,SpringBoot-使用FastJson解析Json資料
十一,SpringBoot-使用FastJson解析Json資料

編輯

⑦,時間格式

修改時間格式,使用fastjson的注解@JSONField

@JSONField(format = "yyyy-MM-dd")
    private      
十一,SpringBoot-使用FastJson解析Json資料
十一,SpringBoot-使用FastJson解析Json資料
十一,SpringBoot-使用FastJson解析Json資料

編輯