I want to set one json field to two attribute in a java pojo. When i use jsonproperty for dublicate attribute in pojo, one field be a null everytime.
My pojo object is;
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;
}
}
My request is;
{
"receiverAccountNo":"566665"
}
My test controller is;
@PostMapping("/test2")
public String test2(@RequestBody PojoTest pojoTest) {
return "OriginalReceiverAccountNo:"+pojoTest.getOriginalReceiverAccountNo()+" ReceiverAccountNo:"+pojoTest.getReceiverAccountNo();
}
When i run code i am getting following response;
OriginalReceiverAccountNo:566665 ReceiverAccountNo:null
I am using jackson-annotation-2.9.0 dependency.How can i resolve this issue?
You can use constructor mapping like this, that sets two properties given one @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;
}
I prefer this method to create immutable objects, but you can keep it mutable if you like
That is not possible. One json field is mapped to exactly one pojo property.
You can however change the behavior of your pojo so that the setter of either one sets the value of the other as well:
@JsonProperty("receiverAccountNo")
public void setOriginalReceiverAccountNo(String originalReceiverAccountNo) {
this.originalReceiverAccountNo = originalReceiverAccountNo;
this.receiverAccountNo = originalReceiverAccountNo;
}
public void setReceiverAccountNo(String receiverAccountNo) {
this.receiverAccountNo = receiverAccountNo;
this.originalReceiverAccountNo = receiverAccountNo;
}
This way both fields in the pojo will have the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With