Spring Boot程式中@JsonIgnoreProperties與@JsonIgnore基本使用
問題由來:
springboot專案中定義了很多類,我們在rest返回中直接返回或者在返回物件中使用這些類,spring已經使用jackson自動幫我們完成這些的to json。但是有時候自動轉的json內容太多,或者格式不符合我們的期望,因此需要調整類的to json過程,或者說希望自定義類的json過程。
解決辦法:
使用@JsonIgnoreProperties、@JsonIgnore、@JsonFormat。
@JsonIgnore註解用來忽略某些欄位,可以用在變數或者Getter方法上,用在Setter方法時,和變數效果一樣。這個註解一般用在我們要忽略的欄位上。
@JsonIgnoreProperties(ignoreUnknown = true),將這個註解寫在類上之後,就會忽略類中不存在的欄位。這個註解還可以指定要忽略的欄位,例如@JsonIgnoreProperties({ “password”, “secretKey” })
@JsonFormat可以幫我們完成格式轉換。例如對於Date型別欄位,如果不適用JsonFormat預設在rest返回的是long,如果我們使用@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”),就返回"2018-11-16 22:58:15"
具體可以參考官方文件
https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html
@JsonIgnoreProperties與@JsonIgnore的主要區別在於, @JsonIgnoreProperties是類級別的, 而@JsonIgnore是變數和方法級別的。
實際程式碼
完整的程式在這裡,歡迎加星,fork。
程式碼簡要說明, User類的fullName 和comment欄位會被@JsonIgnoreProperties註解忽略。address欄位會被@JsonIgnore註解忽略。regDate會按照@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)進行格式轉。
@Data
@JsonIgnoreProperties(value = {"fullName", "comment"})
public class User {
private String id;
private String name;
private String fullName;
private String comment;
private String mail;
@JsonIgnore
private String address;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date regDate;
private Date reg2Date;
}
我們的controller示例程式碼
@ApiOperation(value = "按使用者id刪除", notes="private")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", defaultValue = "2", value = "userID", required = true, dataType = "string", paramType = "path"),
})
@DeleteMapping(value = "/users/{userId}", produces = "application/json;charset=UTF-8")
public User delUser(@PathVariable String userId) {
User user = (User)userSvc.deleteById(userId);
log.info("rest del user={} by id={}", user, userId);
return user;
}
可以看到返回的物件是User,然後comment、fullName、address屬性被忽略了,regDate的格式進行轉換。