@JsonProperty, @JsonIgnore 和 @JsonFormat 注解都是 fasterxml jackson 里面的注解,現(xiàn)在也被 Spring Boot 集成了。
這里需要注意的是將對象轉(zhuǎn)換成json字符串使用的方法是fasterxml.jackson提供的!!
如果使用fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
沒有生效,為啥?
因為fastjson不認(rèn)識@JsonProperty注解呀!所以要使用jackson自己的序列化工具方法
我們在使用上面的注解時,不需要在 pom.xml 顯示的引入 fasterxml jackson 的依賴包。只需要加入如下依賴即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@JsonProperty
用于屬性、setter / getter 方法上,屬性序列化后可重命名
@JsonProperty("image_width")
private Double imageWidth;
@JsonProperty("image_height")
private Double imageHeight;
// 為反序列化期間要接受的屬性定義一個或多個替代名稱,可以與@JsonProperty一起使用
@JsonAlias({"pass_word", "passWord"})
@JsonProperty("pwd")
private String password;
生成的 json 字符串就是image_width和image_height。
@JsonIgnore
屬性使用此注解后,將不被序列化。
@JsonFormat
用于格式化日期
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
//序列化、反序列化時,格式化時間
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;
@JsonInclude,@JsonIgnoreProperties,@JsonIgnore
@Data
//序列化、反序列化忽略的屬性,多個時用“,”隔開
@JsonIgnoreProperties({"captcha"})
//當(dāng)屬性的值為空(null或者"")時,不進(jìn)行序列化,可以減少數(shù)據(jù)傳輸
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class UserVoByJson {
// 序列化、反序列化時,屬性的名稱
// @JsonProperty("userName")
private String username;
// 為反序列化期間要接受的屬性定義一個或多個替代名稱,可以與@JsonProperty一起使用
// @JsonAlias({"pass_word", "passWord"})
// @JsonProperty("pwd")
private String password;
//序列化、反序列化時,格式化時間
// @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;
//序列化、反序列化忽略屬性
// @JsonIgnore
private String captcha;
}
真實案例
{
"rowid": "111111",
"created": "2018-12-27 16:15:25",
"createdby": "1111111",
"lastupd": "2018-12-27 08:25:48",
"lastupdby": "111111",
"modificationnum": 1
}
返回Json參數(shù)字段均為小寫,在接收時,需要按照標(biāo)準(zhǔn)的命名規(guī)則進(jìn)行映射
解決辦法:
創(chuàng)建接收數(shù)據(jù)對象,生成Get\Set方法:,在Set方法上,加上@JsonProperty注解,
@JsonProperty 此注解用于屬性上,作用是把該屬性的名稱序列化為另外一個名稱,如把rowId屬性序列化為rowid,@JsonProperty("rowid")。
private String rowId;
private Date created;
private String createdBy;
private Date lastUpd;
private String lastUpdBy;
?
@JsonProperty("rowId")
public String getRowId() {
return rowId;
}
?
@JsonProperty("rowid")
public void setRowId(String rowId) {
this.rowId = rowId;
}
?
public Date getCreated() {
return created;
}
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setCreated(Date created) {
this.created = created;
}
?
@JsonProperty("createdBy")
public String getCreatedBy() {
return createdBy;
}
?
@JsonProperty("createdby")
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}