我在我的项目中使用Spring boot Jackson依赖项和lombok,作为回应我因为下划线而得到重复的字段
这是我的模型类:
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@ToString
public class TcinDpciMapDTO {
@JsonProperty(value = "tcin")
private String tcin;
@JsonProperty(value = "dpci")
private String dpci;
@JsonProperty(value = "is_primary_tcin_in_dpci_relation")
private boolean is_primaryTcin = true;
}
如果我在is_primaryTcin字段中使用下划线,那么我将获得重复字段的响应
{
"_primaryTcin": true,
"tcin": "12345",
"dpci": "12345",
"is_primary_tcin_in_dpci_relation": true
}
如果我从字段isprimaryTcin删除下划线,那么我得到正确的答复
{
"tcin": "12345",
"dpci": "12345",
"is_primary_tcin_in_dpci_relation": true
}
这是因为下划线吗?但是下划线更适合用于变量名称吗?
解决方法:
这是你的类在delomboking之后的样子:
public class TcinDpciMapDTO {
@JsonProperty("tcin")
private String tcin;
@JsonProperty("dpci")
private String dpci;
@JsonProperty("is_primary_tcin_in_dpci_relation")
private boolean is_primaryTcin = true;
public String getTcin() {
return this.tcin;
}
public String getDpci() {
return this.dpci;
}
public boolean is_primaryTcin() {
return this.is_primaryTcin;
}
public TcinDpciMapDTO setTcin(String tcin) {
this.tcin = tcin;
return this;
}
public TcinDpciMapDTO setDpci(String dpci) {
this.dpci = dpci;
return this;
}
public TcinDpciMapDTO set_primaryTcin(boolean is_primaryTcin) {
this.is_primaryTcin = is_primaryTcin;
return this;
}
public TcinDpciMapDTO() {
}
public String toString() {
return "TcinDpciMapDTO(tcin=" + this.getTcin() + ", dpci=" + this.getDpci() + ", is_primaryTcin=" + this.is_primaryTcin() + ")";
}
}
如果未指定生成的属性名称,则杰克逊通过剥离前缀来生成它,如果使用getter则使用get get,或者在不使用getter的情况下序列化字段时使用Java字段名称.默认情况下,Jackson仅在序列化期间使用getter.因为你把@JsonProperty放在字段上,Jackson使用字段和getter并检查字段是否已经通过匹配生成的属性名序序列化(最后一部分是我的猜测)它不识别字段is_primaryTcin生成的属性和从中生成的属性getter is_primaryTcin()同样(一个内部命名为is_primaryTcin,另一个命名为_primaryTcin) – 请注意,如果将is_primaryTcin重命名为as_primaryTcin,问题就会消失.
标签:lombok,java,spring-boot,jackson
来源: https://codeday.me/bug/20190731/1586950.html