1.使用默认的json转换HttpessageConverter

Json是目前主流的前后端数据传输方式,SpringMVC中使用消息转化器HttpMessageConverter对JSON的转换提供了很好的支持,在SpringBoot中对相关配置做了进一步简化。

pom.xml

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

这个依赖中默认加入了jacjson-databind作为JSON处理器,此时不需要添加额外的Json处理器就可以返回json了。

public class Book {
private String name;
private String author; @JsonIgnore //过滤掉这个属性
protected Float price;
@JsonFormat(pattern = "yyyy-MM-dd") //格式化输出这个属性
private Date publicationDate; //省略getter/setter } @RestController
public class BookController {
@GetMapping("/book")
public Book book() {
Book book = new Book();
book.setAuthor("罗贯中");
book.setName("三国演义");
book.setPrice(30f);
book.setPublicationDate(new Date());
return book;
}
}

结果:

这是Springboot自带的处理方式,如果采用这种方式,对于字段忽略,日期格式化等都可以使用注解实现。
Spring中默认提供的MappingJackson2HttpMessageConverter去实现json转换的。

2.自定义转换器
  常见的JSON处理器除了Jackson-databind,还有Gson和fastjson
2.1使用Gson
  Gson是Google的一个开源的JSON解析框架,使用他之前首先去除默认的jackson-databind,然后加入Gson依赖。

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

  SpringBoot中默认提供了Gson的自动转换类GsonHttpMessageConverterConfiguration,因此可以像使用jackson-databind那样直接使用Gson,但是在Gson进行转换时,如果想对日期数据进行格式化,还需要自定义HttpMessageConverter。

protected static class GsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}

@ConditionalOnMissingBean注解表示当项目中没有提供GsonHttpMessageConverter 时才会使用默认的GsonHttpMessageConverter,所以我们自己写一个  GsonHttpMessageConverter就可以避免没有GsonHttpMessageConverter从而使用默认的了。

@Configuration
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter() {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
//设置Gson解析时日期的格式
builder.setDateFormat("yyyy-MM-dd");
//设置Gson解析时修饰符为protected的字段时过滤掉它
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
//创建Gson对象放入GsonHttpMessageConverter的实例并且返回converter
Gson gson = builder.create();
converter.setGson(gson);
return converter;
}
} public class Book {
private String name;
private String author;
protected Float price; //字段被过滤掉
private Date publicationDate;
}

2.2使用fastjson
阿里巴巴的json解析框架,可以集成到SpringBoot中,不同于Gson,fastjson继承后并不能立即使用,还需要开发者提供HttpMessageConverter后才可以使用。
同样,去除jsckson-databind依赖,加入fastjson依赖

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

配置fasjson的HttpMessageConverter

@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig();
//设置json解析中一些细节,日期格式,数据编码
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
//是否在生成的Json中输出类名
//是否输出value为null的数据
//生成的json格式化
//空集合输出[]而非null
//空字符串输出“”而非null等配置
config.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
); converter.setFastJsonConfig(config);
return converter;
}
}

若输出中文有乱码:spring.http.encoding.force-response=true

对于FastJsonHttpMessageConverter 的配置,还有一种方式

引入spring-boot-starter-web后,他依赖spring-boot-autoconfigure,在这个自动化配置中,有一个WebMvcAutoConfiguration类提供了对SpringMVC最基本的配置如果希望自己配置只需要实现WebMvcConfigurer接口即可。

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
  
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config); converters.add(converter);
}
} 

Jackson相关注解:

使用Jackson相关的注解时一定要注意自己定义的属性命名是否规范。

命名不规范时会失去效果。(例如Ename ,Eage 为不规范命名。“nameE”,“ageE”为规范命名,如果使用@JsonIgnore注解不起效时请注意一下你的属性名字是否规范

1、@JsonIgnoreProperties

此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

写法将此标签加在model 类的类名上 ,可以多个属性也可以单个属性

//生成json时将name和age属性过滤

@JsonIgnoreProperties({"name"},{"age"})

public class  user {

private  String name;

private int age;

}

2、@JsonIgnore

此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

生成json 时不生成age 属性

public class user {

  private String name;

  @JsonIgnore

  private int age;

}

3、@JsonFormat

此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)

4、@JsonSerialize

此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

5、@JsonDeserialize

此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

6、@Transient

如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架默认其注解为@Basic;

//表示该字段在数据库表中没有
@Transient public int getAge() {  return 1+1; }

SpringBoot整合WEB开发--(一)处理JSON返回数据的更多相关文章

  1. springboot整合web开发(整合servlet、filter、listener、访问静态、文件上传)

    整合servlet 1.继承HttpServlet 2.添加@WebServlet注解 @WebServlet(name="FirstServlet",urlPatterns=&q ...

  2. SpringBoot整合WEB开发--(五)自定义错误页

    目的与原理: 处理异常时,若我们想根据实际情况返回不同的页面,@ControllerAdvice与@ExceptionHandler,一般用于处理应用级别的异常,一些容器级别的错误就处理不了,例如Fi ...

  3. SpringBoot整合WEB开发--(十)配置AOP

    简介: SpringBoot框架中对AOP有很好的支持,简单AOP概念: JoinPoint(连接点):类里面可以被增强的方法即为连接点,例如,想修改哪个方法的功能,那么该方法就是一个连接点. Poi ...

  4. SpringBoot整合WEB开发--(九)整合Servlet,Filter,Listener

    简介: 如果需要整合第三方框架时,可能还是不得不使用Servlet,Filter,Listener,Springboot中也有提供支持. @WebServlet("/my") pu ...

  5. SpringBoot整合WEB开发--(八)启动任务系统

    简介: 有一些特殊的任务需要在系统启动时执行,例如配置文件的加载,数据库初始化等操作,如果没有使用SpringBoot,这些问题可以在Listener中解决.SpringBoot提供了两种解决方案:C ...

  6. SpringBoot整合WEB开发--(七)注册拦截器

    1.创建一个拦截器类实现HandlerInterceptor接口,重写其中的3个方法,这拦截器中方法的执行顺序为:preHandle--Controller--postHandle--afterCom ...

  7. SpringBoot整合WEB开发--(六)CROS支持

    简介: CROS(Cross-Origin Resource Sharing)是由W3C制定的一种跨域资源共享技术标准,其目的为了解决前端的跨域请求,在JavaEE开发中,最常见的前端跨域请求解决方案 ...

  8. SpringBoot整合WEB开发--(三)文件上传

    文件上传: Java中文件上传一共涉及到两个组件,CommonsMultipartResolver和StandardServletMultipartResolver,其中CommonsMultipar ...

  9. SpringBoot整合WEB开发--(二)静态资源访问

    1.默认策略: 静态资源的位置一共5个,开发者可以将静态资源放到其中任意一个,分别是: "classpath:/META-INF/resources/", "classp ...

随机推荐

  1. spring boot中通用应用程序属性

    可以在application.properties文件内部application.yml,文件内部或命令行开关中指定各种属性.本附录提供了常见的Spring Boot属性列表以及对使用它们的基础类的引 ...

  2. ADB之安装APK

    一.下载安装adb工具 下载安装,cmd测试是否成功 二.连接设备 1.手机打开USB测试 2.测试连接 三.安装应用 adb -s [设备编号] install [apk的完整路径]  

  3. P3206 [HNOI2010]城市建设 [线段树分治+LCT维护动态MST]

    Problem 这题呢 就边权会在某一时刻变掉-众所周知LCT不支持删边的qwq- 所以考虑线段树分治- 直接码一发 如果 R+1 这个时间修改 那就当做 [L,R] 插入了一条边- 然后删的边和加的 ...

  4. 跨站请求伪造(Cross-site request forgery), 简称为 XSRF

    跨站请求伪造(Cross-site request forgery), 简称为 XSRF,是 Web 应用中常见的一个安全问题.前面的链接也详细讲述了 XSRF 攻击的实现方式. 当前防范 XSRF ...

  5. 【巨杉数据库SequoiaDB】巨杉数据库 v5.0 Beta版 正式发布

    2020年疫情的出现对众多企业运营造成了严重的影响.面对突发状况,巨杉利用长期积累的远程研发协作体系,仍然坚持进行技术创新,按照已有规划­­推进研发工作,正式推出了巨杉数据库(SequoiaDB) v ...

  6. 推荐一本好书:编写可维护的JavaScript(可下载)

    目录 推荐一本好书:编写可维护的JavaScript(可下载) 书摘: 下载: 有些建议: 推荐一本好书:编写可维护的JavaScript(可下载) 书摘: 很多设计模式就是为了解决紧耦合的问题.如果 ...

  7. 树莓派4B遇到的坑

    由于大创需要用到机器学习这些东西,入手了一个树莓派4B(新手没弄过,直接上手最新版果然是有坑的),大佬勿喷

  8. php 对象、json 、XML、数组互转

    对象转json $json=json_encode($postObj,JSON_FORCE_OBJECT); json转对象 $obj=json_encode($json); json转数组 $arr ...

  9. MySQL的修改和删除数据表字段

    MySQL的修改和删除数据表字段 写在前面: 数据库存在的意义:数据存储和数据管理. 数据库:行(数据),列(字段) 注意:本页是解决了列的字段问题.下一页是解决行的数据问题. 注意,所有的字段名,最 ...

  10. maven配置文件pom.xml小记

    1.pom.xml主要描述了项目:包括配置文件:开发者需要遵循的规则,缺陷管理系统,组织和licenses,项目的url,项目的依赖性,以及其他所有的项目相关因素 2.基础设置: <modelV ...