相同的JSON字段在Java POJO中设置为不同的属性

提问

我想在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依赖关系.如何解决此问题?

最佳答案

您可以像这样使用构造函数映射,在给定一个@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;
    }

我更喜欢这种方法来创建不可变的对象,但是如果您愿意的话,可以将其保持可变

评论