Spring boot之JSON(二)

Spring boot 返回json數(shù)據(jù)

編寫實(shí)體類Student

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
 * 這是一個(gè)測(cè)試實(shí)體類
 */
public class Student {
    private String id;
    private String name;
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date   birthdate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }
}

Springboot默認(rèn)使用jackson解析json日期類型序列化格式需要在時(shí)間屬性上加
@JsonFormat(timezone="GMT+8",pattern="yyyy-MM-dd")
是將String轉(zhuǎn)換成Date汁尺,一般前臺(tái)給后臺(tái)傳值時(shí)用
@DateTimeFormat(pattern="yyyy-MM-dd")
是將Date轉(zhuǎn)換成String 一般后臺(tái)傳值給前臺(tái)時(shí)使用

編寫getStudent方法

package com.springboot.backstage.controller;
import com.springboot.backstage.entity.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

//SpringBoot提供了refult風(fēng)格
// @RestController相當(dāng)于@Controller和@ResponseBody
@RestController
public class HellController {

 
    /**
     * Springbootm默認(rèn)使用jackson解析json
     * @return
     */
    @RequestMapping("/getStudent")
    public Student getStudent(){
        Student student =new Student();
        student.setId("1");
        student.setName("張三");
        student.setBirthdate(new Date());
        return student;
    }

}

運(yùn)行main函數(shù)測(cè)試

@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {
  public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}
image.png

這里推薦一個(gè)google瀏覽器插件(JSON Viewer)可以更清楚的展示json數(shù)據(jù)

Spring boot使用FastJson解析JSON數(shù)據(jù)

引入fastjson依賴庫(kù)

 <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.41</version>
 </dependency>

這里要說(shuō)下很重要的話弟蚀,官方文檔說(shuō)的1.2.10以后子檀,會(huì)有兩個(gè)方法支持HttpMessageconvert曹洽,一個(gè)是FastJsonHttpMessageConverter,支持4.2以下的版本双泪,一個(gè)是FastJsonHttpMessageConverter4支持4.2以上的版本坞古,具體有什么區(qū)別暫時(shí)沒有深入研究。這里也就是說(shuō):低版本的就不支持了酱鸭,所以這里最低要求就是1.2.10+吗垮。

第一種方法

第一種方法就是:
(1)啟動(dòng)類繼承extends WebMvcConfigurerAdapter
(2)覆蓋方法configureMessageConverters

代碼

package com.springboot.backstage.controller;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //1.需要先定義一個(gè)convert消息轉(zhuǎn)換的對(duì)象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:要格式化返回的json數(shù)據(jù)
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        //3.處理中文亂碼問題
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //4.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
 public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}

測(cè)試

把Student類的date對(duì)象改成能接收f(shuō)astjson返回的date如果被格式化說(shuō)明已經(jīng)使用fastjson解析
@JSONField(format = "yyyy-MM-dd")
fastjson另一個(gè)參數(shù)可以讓屬性不參與序列化
@JSONField(serialize=false)

package com.springboot.backstage.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;

/**
 * 這是一個(gè)測(cè)試實(shí)體類
 */
public class Student {
    private String id;
    private String name;
    @JSONField(format = "yyyy-MM-dd")
    private Date   birthdate;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }
}
image.png

第二種方法

在這里使用@Bean注入FastJsonHttpMessageConverter

代碼

package com.springboot.backstage.controller;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SpringBootApp  {
    /**
     * 在這里使用@Bean注入FastJsonHttpMessageConverter
     * @return
     */
    @Bean
    public  HttpMessageConverters fastJsonHttpMessageConverter(){
        //1.需要先定義一個(gè)convert消息轉(zhuǎn)換的對(duì)象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //2.添加fastJson的配置信息,比如:要格式化返回的json數(shù)據(jù)
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3.處理中文亂碼問題
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        //4.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);


    }

    public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市凹髓,隨后出現(xiàn)的幾起案子烁登,更是在濱河造成了極大的恐慌,老刑警劉巖蔚舀,帶你破解...
    沈念sama閱讀 222,681評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件饵沧,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡赌躺,警方通過查閱死者的電腦和手機(jī)狼牺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)礼患,“玉大人是钥,你說(shuō)我怎么就攤上這事掠归。” “怎么了悄泥?”我有些...
    開封第一講書人閱讀 169,421評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵虏冻,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我弹囚,道長(zhǎng)厨相,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,114評(píng)論 1 300
  • 正文 為了忘掉前任余寥,我火速辦了婚禮领铐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘宋舷。我一直安慰自己绪撵,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評(píng)論 6 398
  • 文/花漫 我一把揭開白布祝蝠。 她就那樣靜靜地躺著音诈,像睡著了一般。 火紅的嫁衣襯著肌膚如雪绎狭。 梳的紋絲不亂的頭發(fā)上细溅,一...
    開封第一講書人閱讀 52,713評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音儡嘶,去河邊找鬼喇聊。 笑死,一個(gè)胖子當(dāng)著我的面吹牛蹦狂,可吹牛的內(nèi)容都是我干的誓篱。 我是一名探鬼主播,決...
    沈念sama閱讀 41,170評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼凯楔,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼窜骄!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起摆屯,我...
    開封第一講書人閱讀 40,116評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤邻遏,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后虐骑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體准验,經(jīng)...
    沈念sama閱讀 46,651評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評(píng)論 3 342
  • 正文 我和宋清朗相戀三年廷没,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了沟娱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,865評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腕柜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情盏缤,我是刑警寧澤砰蠢,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站唉铜,受9級(jí)特大地震影響台舱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜潭流,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評(píng)論 3 336
  • 文/蒙蒙 一竞惋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧灰嫉,春花似錦拆宛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至根盒,卻和暖如春钳幅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背炎滞。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工敢艰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人册赛。 一個(gè)月前我還...
    沈念sama閱讀 49,299評(píng)論 3 379
  • 正文 我出身青樓钠导,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親击奶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子辈双,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容