spring-boot-json(第三篇)

本文介绍spring-boot返回json格式数据,通过fastjson转化。

1、开发准备

Ø  开发环境jdk1.7或者1.8

Ø  开发工具Eeclipse

Ø  项目管理工具maven

2、创建工作空间

使用idea创建一个module, idea中module相当于eclipse中的项目,名称为spring-boot-json.






创建成功后目录如下:



3、 在pom.xml中引入spring-boot、fastjson的jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.example.springboot</groupId>
   <artifactId>springboot-json</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>springboot-json</name>
   <description>Demo project for Spring Boot</description>

   <!--项目基本属性配置  注释快捷键:Ctrl+shift+正斜杠 ; 格式化: Ctrl+Alt+L -->
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <!-- 引入spring-boot父节点-->
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.1.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <dependencies>
      <!-- 引入spring-boot-web依赖包-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <!-- 引入spring-boot-test测试包-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <!-- 引入json处理包 -->
      <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>1.2.35</version>
      </dependency>
   </dependencies>

   <build>
      <finalName>springboot-json</finalName>
      <plugins>
         <!-- 引入spring tomcat插件包 -->
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>


</project>


4、编写User实体类

package com.example.springboot.json.entity;

import java.util.Date;

public class User {

   private String id;
   private String userName;
   private String password;}

以上就不提供get/set方法


5、编写Controller类

package com.example.springboot.json.controller;

import com.example.springboot.json.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 使用@RestController等价于@Controler @ResponseBody
 *
 * @author wangsh
 * @date 2018/5/4 23:53
 */
@RestController
public class FastJsonController {
   /**
    * 请求映射:http://localhost:8080/hello
    *
    * @return
    */
   @RequestMapping("/hello")
   public String hello() {
      System.out.println("hello...........");
      return "hello";
   }

   /**
    * 请求映射:http://localhost:8080/getUser
    *
    * @return
    */
   @RequestMapping("/getUser")
   public User getUser() {
      User user = new User();
      user.setId("1111111");
      user.setUserName("zhangsan");
      user.setPassword("123");
      user.setCreateTime(new Date());
      return user;
   }
}


6、编写启动类配置fastjosn

fastjson支持方式一:

Ø  启动类继承WebMvcConfigurerAdapter

Ø  覆盖方法configureMessageConverters

package com.example.springboot.json;

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.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * 1.使用fastjson,需要继承WebMvcConfigurerAdapter,覆盖configureMessageConverters方法
 * 
 * @author Administrator
 * 
 */
@SpringBootApplication
public class SpringbootJsonApplication extends WebMvcConfigurerAdapter {

   public static void main(String[] args) {
      // 启动spring容器
      SpringApplication.run(App.class, args);
   }

   @Override
   public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
      super.configureMessageConverters(converters); // 创建fastjson对象
      //创建convert消息转换对象
      FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

      // 添加fastjosn配置信息,设置是否需要格式化
      FastJsonConfig confg = new FastJsonConfig();
      confg.setSerializerFeatures(SerializerFeature.PrettyFormat);
      //添加配置信息到消息对象
      converter.setFastJsonConfig(confg);
      
      converters.add(converter);
   }

}


fastjson支持方式二:

Ø  通过bean注入一个消息对象

package com.example.springboot.json;

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.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringbootJsonApplication {

   public static void main(String[] args) {
      SpringApplication.run(SpringbootJsonApplication.class, args);
   }

   /**
    * 使用bean方式注入fastjson解析器
    *
    * @return
    */
   @Bean
   public HttpMessageConverters fastJsonHttpMessageConverters() {
      // 创建fastjson对象
      FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

      FastJsonConfig confg = new FastJsonConfig();
      // 设置是否需要格式化
      confg.setSerializerFeatures(SerializerFeature.PrettyFormat);
      converter.setFastJsonConfig(confg);
      return new HttpMessageConverters(converter);
   }

}


7、启动运行错误

Information:java: Errors occurred while compiling module 'springboot-json'
Information:javac 7 was used to compile java sources
Information:2018/5/5 0:08 - Compilation completed with 1 error and 0 warnings in 4s 579ms

Error:java: 无效的源发行版: 1.8

以上错误表示jdk版本不对

解决办法:

1、将pom.xml中基本属性jdk版本配置改为1.7


2、修改项目jdk编译版本

Ctrl+Alt+Shift+S 打开项目配置如下:


3、修改项目module编译jdk版本


4、修改部署jdk版本


5、修改项目编译版本

Ctrl+Alt+S 打开设置如下:,选择file->setting->build->compiler->java compiler



8、fastjson启动测试结果


未使用fastjson如下,时间是毫秒值。



修改实体类,通过增加json标示@JSONField(format="yyyy-MM-dd")

public class User {

   private String id;
   private String userName;
   private String password;
   @JSONField(format="yyyy-MM-dd")
   private Date createTime;}

重新启动服务测试如下:


通过以上结果可以看出,时间已经转化为yyyy-MM-dd格式。

猜你喜欢

转载自blog.csdn.net/seashouwang/article/details/80201685
今日推荐