zoukankan      html  css  js  c++  java
  • 峰哥说技术:11-Spring Boot返回JSON

    JSON是目前主流的前后端数据传输方式,但是很多小伙伴在这种开放模式下,对于JSON的使用不是很熟练。私下有人问我,今天峰哥抽空专门写了篇文章来聊聊这个问题。

    峰哥今天带着大家分别采用jackson-databind、gson、fastjson作为JSON的处理器带着大家来学习一下。

    大家都知道,Spring MVC使用消息转换器HttpMessageConverter对json的转换提供了很好的支持。其实在Spring boot对于JSON的处理提供了进一步提供了简化,只要添加web依赖后,由于web依赖中默认添加了jackson-databind作为JSON处理器,因此我们不需要再做更多的处理。下面看案例,做一个具体的说明。

    A)jackson-databind默认实现

    1)创建项目。添加web支持

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    2)创建实体类Book

    public class Book {
            private Integer id;
            private String name;
            private String author;
            @JsonFormat(pattern = "yyyy-MM-dd") //日期字段格式化
            private Date pubTime;
            @JsonIgnore  //忽略转换字段
            public Double price;

            public Book() {
        }

        public Book(Integer id, String name, String author, Date pubTime, Double price) {
            this.id = id;
            this.name = name;
            this.author = author;
            this.pubTime = pubTime;
            this.price = price;
        }

        //getter和setter省略...

    }

    注意红色字体部分,对于要转换忽略的字段和日期字段的注解用法。

    3)填写IndexController

    @Controller
    public class IndexController {
        @GetMapping("/book")
        @ResponseBody
        public Book getBook(){
            return new Book(1,"三国演义","罗贯中",new Date(),67.6D);
        }
    }

    4)在浏览器输入:http://localhost:8080/book,中进行测试,结果如下:

     

    B)自定义类型转换器gson实现

    由于Spring Boot中默认提供了GsonHttpMessageConvertersConfiguration自动化配置,可以直接使用Gson,但是如果待转换的数据中包含日期格式,那么我们需要GsonHttpMessageConverter即可。代码如下:

    1)pom.xml中排除默认的jackson-databind支持。同时添加gson依赖。

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
              <exclusions>
                  <exclusion>
                      <artifactId>jackson-databind</artifactId>
                      <groupId>com.fasterxml.jackson.core</groupId>
                  </exclusion>
              </exclusions>
    </dependency>
    <dependency>
              <groupId>com.google.code.gson</groupId>
              <artifactId>gson</artifactId>
    </dependency>

     

    2)编写MyJsonConfig配置类,在该类中注入GsonHttpMessageConverter对象。

    @Configuration
    public class JsonConfig {
        @Bean
        public GsonHttpMessageConverter gsonHttpMessageConverter(){
            GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
            GsonBuilder gsonBuilder=new GsonBuilder();
            gsonBuilder.setDateFormat("yyyy-MM-dd");
            //对于转换对象中的protected字段给排除转换
            //gsonBuilder.excludeFieldsWithModifiers(Modifier.PROTECTED);
            Gson gson = gsonBuilder.create();
            converter.setGson(gson);
            return converter;
        }
    }

    3)修改Book实体类,去掉相关注解。

    public class Book {
            private Integer id;
            private String name;
            private String author;
            private Date pubTime;
            public Double price;
            //构造方法和getter和setter省略...

    }

    4)在浏览器中进行测试。

     

    对于Java配置类的使用,大家经过几个练习后,应该也没有什么问题。大家多练习。

    C)自定义类型转换器fastjson实现

    fastjson是阿里巴巴的一个开源JSON解析框架,是目前JSON解析速度最快的开源框架,该框架也可以被集成到Spring Boot中。不同于gson,fastjson集成完后不能马上使用,需要提供HttpMessageConverter后才能使用。

    使用的步骤如下。

    1)pom.xml中移除jackson-databind依赖,添加fastjson依赖。

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
              <exclusions>
                  <exclusion>
                      <artifactId>jackson-databind</artifactId>
                      <groupId>com.fasterxml.jackson.core</groupId>
                  </exclusion>
              </exclusions>
    </dependency>
    <dependency>
              <groupId>com.alibaba</groupId>
              <artifactId>fastjson</artifactId>
              <version>1.2.47</version>
    </dependency>

    2)编写配置类MyFastJsonConfig

    @Configuration
    public class MyFastJsonConfig {
        @Bean
        public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            FastJsonConfig config=new FastJsonConfig();
            config.setDateFormat("yyyy-MM-dd");
            config.setCharset(Charset.forName("UTF-8"));
            config.setSerializerFeatures(
                    //是否输出类名
                    //SerializerFeature.WriteClassName,
                    //是否输出value为null的数据
                    SerializerFeature.WriteMapNullValue,
                    //是否生成JSON的格式化
                    SerializerFeature.PrettyFormat,
                    //是否输出空的List集合
                    SerializerFeature.WriteNullListAsEmpty,
                    //是否输出null字符串
                    SerializerFeature.WriteNullStringAsEmpty
                    );
            converter.setFastJsonConfig(config);
            return converter;
        }
    }

    3)application.properties中配置响应编码。否则会有中文乱码。

    spring.http.encoding.force-response=true

    4)在浏览器中输入http://localhost:8080/book,进行测试,结果如下。

     

  • 相关阅读:
    使用select2插件并添加拼音首字母检索
    sql id 或使用nolock
    .net 开源组件
    EF 创建数据库的策略 codefist加快效率!【not oringin!】
    个人拾遗!数组的拷贝等
    编程拾遗:集合类型的函数,返回值,如果没有,就返回默认集合new,或者 default(T)好一些。
    C# datatable to list
    npoi导出excel 导出List<T>
    display:inline、block、inline-block的区别 摘】
    ie下,jquery为动态添加的节点添加事件,用live
  • 原文地址:https://www.cnblogs.com/027kgc/p/12453963.html
Copyright © 2011-2022 走看看