java 字段名重复,java – JSON响应中的重复字段

我在我的项目中使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值