Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same json field set to different attribute in java pojo

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?

like image 310
mertaksu Avatar asked Jul 08 '26 12:07

mertaksu


2 Answers

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

like image 98
Brad Avatar answered Jul 10 '26 03:07

Brad


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.

like image 35
f1sh Avatar answered Jul 10 '26 03:07

f1sh