欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot返回JSON

程序员文章站 2022-05-15 10:29:38
[TOC] 1、SpringBoot返回JSON简介 随着web开发前后端分离技术的盛行,json是目前主流的前后端数据交互方式,使用json数据进行交互需要对json数据进行转换解析,需要用到一些json处理器,常用的json处理器有: jackson databind,SpringBoot默认的 ......

1、springboot返回json简介

随着web开发前后端分离技术的盛行,json是目前主流的前后端数据交互方式,使用json数据进行交互需要对json数据进行转换解析,需要用到一些json处理器,常用的json处理器有:

  • jackson-databind,springboot默认的json处理器
  • gson,是google的一个开源框架
  • fastjson,目前解析速度最快的开源解析框架,由阿里开发

下面分别介绍如何在springboot中整合三大json解析框架。

2、整合jackson-databind

jackson-databind是springboot默认集成在web依赖中的框架,因此我们只需要引入spring-boot-starter-web依赖,就可以返回json数据:

接着上篇文章中的demo继续修改demo,先看下代码框架:

SpringBoot返回JSON

下面开始修改demo,返回json数据,首先在pojo下创建一个good实体类,并且可以通过注解来解决日期格式等需求:

package com.gongsir.springboot02.pojo;

import com.fasterxml.jackson.annotation.jsonformat;
import com.fasterxml.jackson.annotation.jsonignore;

import java.util.date;

public class good {
    private integer id;
    private string name;
    @jsonignore
    private double price;
    @jsonformat(pattern = "yy-mm-dd")
    private date dealdate;

    public integer getid() {
        return id;
    }

    public void setid(integer id) {
        this.id = id;
    }

    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public double getprice() {
        return price;
    }

    public void setprice(double price) {
        this.price = price;
    }

    public date getdealdate() {
        return dealdate;
    }

    public void setdealdate(date dealdate) {
        this.dealdate = dealdate;
    }
}

然后在controller包下创建一个goodcontroller,在方法上加上@responsebody注解(也可以直接使用@restcontroller注解整个类)即可返回json信息:

@controller
@requestmapping(value = "/good")
public class goodcontroller {

    @getmapping(path = "/get")
    @responsebody
    public good getgood(){
        good good = new good();
        good.setid(1);
        good.setname("macbook pro 2019");
        good.setprice(16999.99);
        good.setdealdate(new date());
        return good;
    }
}

此时可以使用浏览器或者postman工具来查看结果,运行项目,调用http://localhost:8080/good/get接口:

SpringBoot返回JSON

3、整合gson

使用gson需要将springboot默认依赖的jackson-databind除去,然后引入gson:

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
            <!--除去jackson-databind依赖-->
            <exclusions>
                <exclusion>
                    <groupid>com.fasterxml.jackson.core</groupid>
                    <artifactid>jackson-databind</artifactid>
                </exclusion>
            </exclusions>
        </dependency>
        <!--引入gson依赖-->
        <dependency>
            <groupid>com.google.code.gson</groupid>
            <artifactid>gson</artifactid>
        </dependency>

创建一个gson配置:

package com.gongsir.springboot02.configuration;

import com.google.gson.gson;
import com.google.gson.gsonbuilder;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.http.converter.json.gsonhttpmessageconverter;

import java.lang.reflect.modifier;

@configuration
public class gsonconfig {
    @bean
    gsonhttpmessageconverter gsonhttpmessageconverter(){
        gsonhttpmessageconverter gsonhttpmessageconverter = new gsonhttpmessageconverter();
        gsonbuilder builder = new gsonbuilder();
        //设置解析的日期格式
        builder.setdateformat("yyyy-mm-dd");
        //设置忽略字段,忽略修饰符为protected的字段属性
        builder.excludefieldswithmodifiers(modifier.protected);
        gson gson = builder.create();
        gsonhttpmessageconverter.setgson(gson);
        return gsonhttpmessageconverter;
    }
}

修改good,java:

package com.gongsir.springboot02.pojo;

import java.util.date;

public class good {
    protected integer id;
    private string name;
    private double price;
    private date dealdate;

    public integer getid() {
        return id;
    }

    public void setid(integer id) {
        this.id = id;
    }

    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public double getprice() {
        return price;
    }

    public void setprice(double price) {
        this.price = price;
    }

    public date getdealdate() {
        return dealdate;
    }

    public void setdealdate(date dealdate) {
        this.dealdate = dealdate;
    }
}

启动项目,再次访问http://localhost:8080/good/get接口:

SpringBoot返回JSON

4、整合fastjson

引入fastjson依赖,修改刚刚的pom.xml:

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
            <!--除去jackson-databind依赖-->
            <exclusions>
                <exclusion>
                    <groupid>com.fasterxml.jackson.core</groupid>
                    <artifactid>jackson-databind</artifactid>
                </exclusion>
            </exclusions>
        </dependency>
        <!--引入fastjson依赖-->
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>fastjson</artifactid>
            <version>1.2.47</version>
        </dependency>

配置fastjson有两种方法,方法一:自定义myfastjsonconfig,提供fastjsonhttpmessageconverter bean:

package com.gongsir.springboot02.configuration;

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.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.http.mediatype;

import java.nio.charset.charset;
import java.util.arraylist;
import java.util.list;

@configuration
public class myfastjsonconfig {
    @bean
    fastjsonhttpmessageconverter fastjsonhttpmessageconverter(){
        fastjsonhttpmessageconverter converter = new fastjsonhttpmessageconverter();
        fastjsonconfig config = new fastjsonconfig();
        //升级之后的fastjson(1.2.28之后的版本)需要手动配置mediatype,否则会报错
        list<mediatype> supportedmediatypes = new arraylist<>();
        supportedmediatypes.add(mediatype.application_json);
        supportedmediatypes.add(mediatype.application_json_utf8);
        supportedmediatypes.add(mediatype.application_atom_xml);
        supportedmediatypes.add(mediatype.application_form_urlencoded);
        supportedmediatypes.add(mediatype.application_octet_stream);
        supportedmediatypes.add(mediatype.application_pdf);
        supportedmediatypes.add(mediatype.application_rss_xml);
        supportedmediatypes.add(mediatype.application_xhtml_xml);
        supportedmediatypes.add(mediatype.application_xml);
        supportedmediatypes.add(mediatype.image_gif);
        supportedmediatypes.add(mediatype.image_jpeg);
        supportedmediatypes.add(mediatype.image_png);
        supportedmediatypes.add(mediatype.text_event_stream);
        supportedmediatypes.add(mediatype.text_html);
        supportedmediatypes.add(mediatype.text_markdown);
        supportedmediatypes.add(mediatype.text_plain);
        supportedmediatypes.add(mediatype.text_xml);
        converter.setsupportedmediatypes(supportedmediatypes);

        config.setdateformat("yyyy-mm-dd");
        config.setcharset(charset.forname("utf-8"));
        config.setserializerfeatures(
                //json格式化
                serializerfeature.prettyformat,
                //输出value为null的数据
                serializerfeature.writemapnullvalue
        );
        converter.setfastjsonconfig(config);
        return converter;
    }
}

方法二:实现webmvcconfigurer接口,重写configuremessageconverters方法:

package com.gongsir.springboot02.configuration;

import com.alibaba.fastjson.serializer.serializerfeature;
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.webmvcconfigurer;

import java.nio.charset.charset;
import java.util.arraylist;
import java.util.list;

@configuration
public class fastjsonconfig implements webmvcconfigurer {
    @override
    public void configuremessageconverters(list<httpmessageconverter<?>> converters) {
        fastjsonhttpmessageconverter converter = new fastjsonhttpmessageconverter();
        com.alibaba.fastjson.support.config.fastjsonconfig config = new com.alibaba.fastjson.support.config.fastjsonconfig();
        //升级之后的fastjson(1.2.28之后的版本)需要手动配置mediatype,否则会报错
        list<mediatype> supportedmediatypes = new arraylist<>();
        supportedmediatypes.add(mediatype.application_json);
        supportedmediatypes.add(mediatype.application_json_utf8);
        supportedmediatypes.add(mediatype.application_atom_xml);
        supportedmediatypes.add(mediatype.application_form_urlencoded);
        supportedmediatypes.add(mediatype.application_octet_stream);
        supportedmediatypes.add(mediatype.application_pdf);
        supportedmediatypes.add(mediatype.application_rss_xml);
        supportedmediatypes.add(mediatype.application_xhtml_xml);
        supportedmediatypes.add(mediatype.application_xml);
        supportedmediatypes.add(mediatype.image_gif);
        supportedmediatypes.add(mediatype.image_jpeg);
        supportedmediatypes.add(mediatype.image_png);
        supportedmediatypes.add(mediatype.text_event_stream);
        supportedmediatypes.add(mediatype.text_html);
        supportedmediatypes.add(mediatype.text_markdown);
        supportedmediatypes.add(mediatype.text_plain);
        supportedmediatypes.add(mediatype.text_xml);
        converter.setsupportedmediatypes(supportedmediatypes);

        config.setdateformat("yyyy-mm-dd");
        config.setcharset(charset.forname("utf-8"));
        config.setserializerfeatures(
                //json格式化
                serializerfeature.prettyformat,
                //输出value为null的数据
                serializerfeature.writemapnullvalue
        );
        converter.setfastjsonconfig(config);
        //将converter加入到converters
        converters.add(converter);
    }
}

启动项目,再次调用接口:

SpringBoot返回JSON