杰克逊相同值对应两个不同属性

huangapple go评论46阅读模式
英文:

Jackson same value for two different attributes

问题

在Spring 1.4.5应用程序中,我在控制器中接收数据,代码如下:

@PostMapping(value = ENDPOINT, consumes = "application/json")
public ResponseEntity<?> post(@RequestBody Email email) {

其中,Email类有一个属性:

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@Email
private String mail;

由于属性上的READ_ONLY,尽管控制器接收到了邮件(我通过拦截器进行了检查),但控制器不会将其选取。

我尝试通过新属性来复制mail

@JsonProperty("mail")
private String from;

但是我遇到了JsonMappingException,提示"Conflicting getter definitions for property"。

如何才能提取传入JSON中的邮件呢?

英文:

In a Spring 1.4.5 application I receive data in a Controller with:

@PostMapping(value = ENDPOINT, consumes= &quot;application/json&quot;)
public ResponseEntity&lt;?&gt; post(@RequestBody Email email) {

Where Email has an attribute

@JsonPropery(access = JsonProperty.Access.READ_ONLY)
@Email
private String mail;

The Controller receives a mail (I checked with an Interceptor) but it is not picked in the Controller due to the READ_ONLY that I do not dare to remove (it's been in production for years).

I tried to duplicate mail with a new attribute

@JsonPropery(&quot;mail&quot;)
private String from;

but I get JsonMappingException Conflicting getter definitions for property

How can I pick the mail existing in the incoming json?

答案1

得分: 0

已经行之有效的解决方案是不创建新属性的getter方法:

@JsonPropery(access = JsonProperty.Access.READ_ONLY)
@Email
private String mail;

@JsonPropery("mail")
private String from;

private String getMail() {
   return mail;
}
private void setMail(String mail){
   this.mail = mail;
}

private String calcFrom() {
   return from;
}
private void setFrom(String from) {
   this.from = from;
}
英文:

The solution that has worked has been not creating a getter for the new propery:

@JsonPropery(access = JsonProperty.Access.READ_ONLY)
@Email
private String mail;

@JsonPropery(&quot;mail&quot;)
private String from;

private String getMail() {
   return mail;
}
private void setMail(String mail){
   this.mail = mail;
}

private String calcFrom() {
   return from;
}
private void setFrom(String from) {
   this.from = from;
}

huangapple
  • 本文由 发表于 2023年4月17日 15:50:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定