SpringBoot json
本篇文章主要介绍SpringBoot json配置内容。如果文章中有错误或不明确的地方,请大家望指正,谢谢!
SpringBoot 集成了三种json映射库
-
Gson
-
Jackson
-
JSON-B
首选Jackson。在spring-boot-starter-json中配置了jackson的资源包
代码
User.java
package com.stone.springboot.study; import java.util.Date; public class User { private String name; private int age; private String sex; private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
HelloController.java
package com.stone.springboot.study;
import java.util.Date;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@GetMapping("greet")
public String greet() {
return "hello";
}
@GetMapping("user")
public User user() {
User user = new User();
user.setName("tom");
user.setAge(1);
user.setBirthday(new Date());
user.setSex("MALE");
return user;
}
}
启动项目,访问:http://127.0.0.1:8080/user
输出结果:
{"name":"tom","age":1,"sex":"MALE","birthday":"2021-01-08T07:42:53.130+00:00"}
全局jackson日期配置
application.yaml 指定时区和日志输出格式
spring:
jackson:
dateFormat: yyyy-MM-dd HH:mm:ss
timeZone: GMT+8
重新启动项目,访问:http://127.0.0.1:8080/user
输出结果:
{"name":"tom","age":1,"sex":"MALE","birthday":"2021-01-08 15:44:26"}
属性注解配置
user.java 添加注解
@JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8") private Date birthday;
注:优先级高
重新启动项目,访问:http://127.0.0.1:8080/user
输出结果:
{"name":"tom","age":1,"sex":"MALE","birthday":"2021-01-08"}
Jackson配置属性(JacksonProperties)
| 属性 | 默认值 | 说明 |
| dateFormat | 输出的日期格式或者指定的date format类的全类名 | |
| propertyNamingStrategy | 属性命名规则 示例:UPPER_CAMEL_CASE 驼峰首字母大写 | |
| visibility | 设置一些方法的可见性 | |
| serialization | 序列化配置 | |
| deserialization | 反序列化配置 | |
| mapper | jaskson通用特性的开关 | |
| parser | jaskson 转换特性的开关 | |
| generator | jaskson 生成特性的开关 | |
| defaultPropertyInclusion | 序列化时包含输出那些类型属性 | |
| timeZone | 时区 | |
| locale | 语言 |
示例不返回值为null的属性
application.yaml
spring:
jackson:
dateFormat: yyyy-MM-dd HH:mm:ss
timeZone: GMT+8
propertyNamingStrategy: UPPER_CAMEL_CASE
defaultPropertyInclusion: NON_NULL
user.java
@GetMapping("user")
public User user() {
User user = new User();
user.setName("tom");
user.setAge(1);
user.setBirthday(new Date());
return user;
}
输出结果:
{"Name":"tom","Age":1,"Birthday":"2021-01-08"}
输出缩进:
applcation.yaml
spring:
jackson:
dateFormat: yyyy-MM-dd HH:mm:ss
timeZone: GMT+8
propertyNamingStrategy: UPPER_CAMEL_CASE
defaultPropertyInclusion: NON_NULL
serialization:
INDENT_OUTPUT: true
输出结果:
{
"Name" : "tom",
"Age" : 1,
"Birthday" : "2021-01-08"
}
浙公网安备 33010602011771号