我想在java pojo中将一个json字段设置为两个属性。当我在pojo中将jsonproperty用于dublicate属性时,每次都有一个字段为null。
我的pojo对象是;
public class PojoTest {
private String receiverAccountNo;
private String originalReceiverAccountNo;
@JsonProperty("receiverAccountNo")
public String getOriginalReceiverAccountNo() {
return originalReceiverAccountNo;
}
@JsonProperty("receiverAccountNo")
public void setOriginalReceiverAccountNo(String originalReceiverAccountNo) {
this.originalReceiverAccountNo = originalReceiverAccountNo;
}
public String getReceiverAccountNo() {
return receiverAccountNo;
}
public void setReceiverAccountNo(String receiverAccountNo) {
this.receiverAccountNo = receiverAccountNo;
}
}
我的要求是;
{
"receiverAccountNo":"566665"
}
我的测试控制器是;
@PostMapping("/test2")
public String test2(@RequestBody PojoTest pojoTest) {
return "OriginalReceiverAccountNo:"+pojoTest.getOriginalReceiverAccountNo()+" ReceiverAccountNo:"+pojoTest.getReceiverAccountNo();
}
当我运行代码时,我得到以下响应;
OriginalReceiverAccountNo:566665 ReceiverAccountNo:null
我正在使用jackson-annotation-2.9.0依赖性。如何解决此问题?
答案 0 :(得分:3)
您可以像这样使用构造函数映射,在给定一个@JsonProperty
的情况下设置两个属性
public class Pojo
{
private final String receiverAccountNo;
private final String originalReceiverAccountNo;
@JsonCreator
public Observation(
@JsonProperty("receiverAccountNo") String value)
{
this.receiverAccountNo = value;
this.originalReceiverAccountNo = value;
}
我更喜欢这种方法来创建不可变的对象,但是如果您愿意的话,可以将其保持可变状态
答案 1 :(得分:1)
那是不可能的。一个json字段恰好映射到一个pojo属性。
不过,您可以更改pojo的行为,以便其中一个的设置者也可以设置另一个的值:
@JsonProperty("receiverAccountNo")
public void setOriginalReceiverAccountNo(String originalReceiverAccountNo) {
this.originalReceiverAccountNo = originalReceiverAccountNo;
this.receiverAccountNo = originalReceiverAccountNo;
}
public void setReceiverAccountNo(String receiverAccountNo) {
this.receiverAccountNo = receiverAccountNo;
this.originalReceiverAccountNo = receiverAccountNo;
}
通过这种方式,pojo中的两个字段将具有相同的值。