spring boot新手教程之使用FastJson解析JSON数据以及解决返回中文乱码问题

Spring  boot  介绍:

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

Spring  boot  特点:

1. 创建独立的Spring应用程序
2. 嵌入的Tomcat,无需部署WAR文件
3. 简化Maven配置
4. 自动配置Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置
6. 绝对没有代码生成和对XML没有要求配置
以上内容均来自 百度百科
前言:本人新手一枚,初学Spring  boot ,也是第一次写博客,不好之处望见谅微笑
本章内容介绍了使用FastJson解析JSON数据以及解决返回中文乱码问题,实际项目中还包含热部署,连接数据库等其他模块
在这里给大家提供一个视频链接,适合Spring  boot新手学的, 感谢林祥纤大神 http://412887952-qq-com.iteye.com/blog/2344171
现在开始进入正题:
在这里我使用的开发工具是Intelli IDEA,官方工具下载地址 https://www.jetbrains.com/idea/ ,建议大家也用这个,毕竟eclipse 已      经在逐步淘汰了!微笑
---------------------------------------这是一条分割线---------------------------------------

项目结构


上图中的项目结构已经很清晰明了了,这一章真正用到的类并不多,数据库部分我就不晒了,想要整个项目的等下在下面我会贴出项目地址,还有就是大家别像我一样文件乱命名,这样是不规范的大笑



---------------------------------------这是一条分割线---------------------------------------

main 程序入口代码

package com.spring;

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指定为spring boot应用程序
 */
@SpringBootApplication
public class main extends WebMvcConfigurerAdapter{
    /**
     * 1.需要先定义一个convert 转换消息的对象
     * 2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
     * 3.在convert中添加配置信息
     * 4.将convert添加到converters当中
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        super.configureMessageConverters(converters);
        //1.需要先定义一个convert 转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
       // 4.将convert添加到converters当中
        converters.add(fastConverter);

    }

    public  static  void  main(String[] args){
	//这里是程序运行入口,
        SpringApplication.run(main.class,args);
    }
}
 
 
从上面代码可以看出,中文乱码的代码并不多,但是很多博客都是没有写出解决中文乱码问题。还有就是程序运行的方式共有多种,等下我会贴出来
 
 
 
 
 
 
 
 
---------------------------------------这是一条分割线---------------------------------------

 
 
pow依赖文件代码:
 
 
<?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.springStudy</groupId>
    <artifactId>spring-boot-hello</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--spring boot 父节点依赖,引入这个以后相关的引入就不需要添加Version配置,spring boot会自动选择最合适的版本进行添加-->
    <parent>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.2.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--指定JDK版本,默认是1.6-->
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

         <!--spring-boot-starter-web:提供了mvc aop依赖包 -->
            <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
               <version>1.5.6.RELEASE</version>
            </dependency>
 	    <!--fastjson依赖包-->
<dependency>  
    		 <groupId>com.alibaba</groupId>      
     		 <artifactId>fastjson</artifactId>       
    		 <version>1.2.35</version>   
    	   </dependency>   
   	   <dependency>      
    		 <groupId>org.springframework</groupId>     
     		<artifactId>spring-web</artifactId>       
		<version>4.3.10.RELEASE</version>     
  	   </dependency>     
      </dependencies> 
</project>

上面代码中,一共只有三个依赖,项目中有六个,还有连接数据库、热部署我没贴出来,想要全部代码等下我会贴出地址。
如果在代码编写过程中,系统提示找不到这个类、代码报错,那就是没有正确依赖到,可以在工具中添加依赖。还有就是下面的依赖也是可以不指定版本号的,
指定也没关系,可以不指定是因为你添加了父节点
<!--spring boot 父节点依赖,引入这个以后相关的引入就不需要添加Version配置,spring boot会自动选择最合适的版本进行添加-->
    <parent>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.2.RELEASE</version>
    </parent>
下面是添加依赖步骤,萌新专属,老手跳过大笑

第一步

第二步

第三步

第四步

第五步

在这里就可以搜索到你需要的架包了,学到android的就会发现其实这个操作和sutido是一样的。
 
 
在这里添加这几个就够了

 
 
---------------------------------------这是一条分割线---------------------------------------

 
 
 
 
 
 
接下来是实体类demo代码:
 
 
 
 
package com.spring;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;

/**
 * 测试实体类
 */
public class demo {
    private int id;
    private String name;
    //测试fasonjson是否部署成功
    @JSONField(format = "yyyy-MM-dd HH:mm")
    private Date createTime;
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * 不想返回这个属性可通过不序列化
     */
    @JSONField(serialize = false)
    private String remarks;

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
在这里我就没什么好说的了,就是普通的实体类,如果你不想让某个属性在网页中展示出来,只需将它不序列化就可以了
代码中添加这个属性@JSONField(serialize = false)
如下图

继续往下看你们会看到效果

---------------------------------------这是一条分割线---------------------------------------

 
 
HelloController代码
package com.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 *@RestController等价于@Controller和@ResponseBody
 */
@RestController
public class HelloController {

    /**
     * 使用@RequestMapping建立请求映射
     * @return
     */
    @RequestMapping("/test")
    public  String hello(){
        return  "HelloWord";
    }

    @RequestMapping("/test2")
    public  String hello2(){
        return "hello31";
    }

    /**
     * spring boot 默认使用的json解析框架是jackson
     * @return
     */
    @RequestMapping("getdemo")
    public  demo getDemo(){
        demo demo=new demo();
        demo.setId(1);
        demo.setName("洪文");
        demo.setCreateTime(new Date());
        demo.setRemarks("备注信息");
        return  demo;
    }
}
这里的话通过
@RequestMapping("你想要的地址")
在网页中来设置访问地址,默认访问地址是
http://ip:port/spring-boot
	默认ip为 127.0.0.1
	默认port为 8080
	spring-boot  这是你的项目名字

举个例子来说
下图是要返回的内容和请求拼接地址
返回的内容:HelloWord
请求地址:
127.0.0.1:8080/test
如下图

运行项目后这是网页输入显示的结果
当程序报错或访问地址错误时,我们不希望打开页面显示的是404,这时候异常捕捉类就派上用场了,这是未加上捕捉类后的画面,代码往下翻微笑
如下图,这是地址错误且没有异常捕捉类的情况下
下图是加上了异常捕捉类

一对比就很清晰明了
---------------------------------------这是一条分割线---------------------------------------

 
 

异常捕捉类GlobalDefaultExceptionHandler代码:

package com.spring.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕捉类
 * 如果返回的是View---方法的返回值是ModelAndView
 * 如果返回的是String或者Json数据,那么需要在方法上添加@ResponseBody注解
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public  String defaultExceptionHandler(HttpServletRequest request,Exception e){
        //ModelAndView 介绍模板引擎
//        ModelAndView modelAndView=new ModelAndView();
//        modelAndView.setViewName(iewName);
        return  "对不起,服务器繁忙,请稍后再试";
    }

}


可以看到我们返回了一个“对不起,服务器繁忙,请稍后再试”字符串,上图网页中也是出现了这个字符串。

接下来是中文乱码问题,我们加入这段内容,代码在main.class里面,往下翻微笑


然后网页中返回的是正常的中文,中文乱码的界面我就不贴了,遇到了你们就知道了微笑

下图是正常返回中文的界面


返回的内容也是我们之前在代码中自己定义的



看到这里或许有人会问了,你不是写了四个参数吗,怎么只返回了三个参数呢,备注信息呢,

这个呢,我们前面说过了微笑

@JSONField(serialize = false)
这个属性设置了不通过序列化,当然不会显示出来了
如下图

需要返回就设置为true,默认为true,一般不写!微笑
 
 

 
 
---------------------------------------这是一条分割线---------------------------------------

接下来是main.class程序入口代码


package com.spring;

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指定为spring boot应用程序
 */
@SpringBootApplication
public class main extends WebMvcConfigurerAdapter{
    /**
     * 1.需要先定义一个convert 转换消息的对象
     * 2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
     * 3.在convert中添加配置信息
     * 4.将convert添加到converters当中
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        super.configureMessageConverters(converters);
        //1.需要先定义一个convert 转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
       // 4.将convert添加到converters当中
        converters.add(fastConverter);

    }

    public  static  void  main(String[] args){
        SpringApplication.run(main.class,args);
    }
}
 
 
最后贴上程序运行的多种方法,防止很多萌新不会,老手跳过,例如我大笑
第一种

第二种
第三种

 
 
上面二三两种方法只限运行过程序了微笑,第一次是要选择运行项目的

 
 
到这里就基本结束了,写的不好望见谅!!!
完整项目地址,码云直达链接:https://gitee.com/blue-hair/springboothello.git
百度云盘直达链接:	链接: http://pan.baidu.com/s/1pLNr0Pd  密码:1nu2
Github直达链接: https://github.com/Blue-Hair/Springboothello
链接失效也请及时回复微笑
有问题请直接在下文评论联系,我看到会及时回复的微笑
 
 
 
 
 
 
 
 
 
 
人所缺乏的不是才干而是志向,不是成功的能力而是勤劳的意志。 —— 部尔卫







猜你喜欢

转载自blog.csdn.net/a295268305/article/details/77528579