写在最前面:
官方github地址:
https://github.com/FasterXML/jackson-databind/wiki
JackSon注解使用引入:
- 我们先看一段代码:UserController代码中的信息
package zone.reborn.springbootstudy.controller;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import zone.reborn.springbootstudy.entity.User;
/**
* @author 作者: reborn
* @version 创建时间: 2018年7月15日 下午3:59:45
* @description 类说明:
*/
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/testUser", method = RequestMethod.GET)
//@ResponseBody
public Object getUser() {
User user = new User();
user.setName("reborn");
user.setPassword("reborn");
user.setAge(18);
user.setBirthday(new Date());
//user.setDesc("MVC模式的前端请求返回配置。");
return user;
}
}
- 在上述代码中我们可以看到我们使用了@RestController当我们返回user对象时底层会调用Jackson进行数据转换成json的数据形式。所以我们可以在实体类中进行Jackson注解的使用。
Jackson常用的注解使用和使用场景:
- 接下来我们在看一段代码,这段代码是常用注解在实体类User中的简单使用:
package zone.reborn.springbootstudy.entity;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* @author 作者: reborn
* @version 创建时间: 2018年7月15日 下午3:59:45
* @description 类说明:用户实体类
*/
public class User {
private String name;
@JsonIgnore // 利用底层jackson注解
private String password;
private Integer age;
@JsonFormat(pattern = "yy-MM-dd HH:mm:ss a", locale = "zh", timezone = "GMT+8")//yy-MM-dd HH:mm:ss
private Date birthday;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
单独拿出来,聊聊:
- @JsonIgnore 忽略此属性,比如password我并不想返回给前端,就可以添加此注解
- @JsonFormat(pattern = "yy-MM-dd HH:mm:ss a", locale = "zh", timezone = "GMT+8") 进行数据格式化
- @JsonInclude(JsonInclude.Include.NON_NULL) 如果此字段为null不返回该字段数据。
- @JsonProperty(value = "user_name") 指定序列化时的字段名,默认使用属性名
- @JsonUnwrapped(prefix = "user_")
把成员对象中的属性提升到其容器类,并添加给定的前缀,比如上例中: User类中有name和age两个属性,不使用此注解则序列化为:
... "user": { "name": "xxx", "age": 22 } ...
使用此注解则序列化为:
... "user_name": "xxx", "user_age": 22, ..
-
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id") 作用于类或属性上,被用来在序列化/反序列化时为该对象或字段添加一个对象识别码,通常是用来解决循环嵌套的问