反序列化时忽略属性 [英] Ignoring property when deserializing

查看:523
本文介绍了反序列化时忽略属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的界面,其中包含属性的getter和setter。

I have a simple interface with getter and setter for a property.

public interface HasMoney { 

      Money getMoney();

      void setMoney(Money money);

 }

我有另一个实现此接口的UserAccount类。

I have another class UserAccount which implements this interface.

public class UserAccount implements HasMoney {

       private Money money;

       @Override
       Money getMoney() // fill in the blanks

       @Override
       void setMoney(Money money) // fill in the blanks

}

我的问题是我要序列化钱财产但是反序列化时忽略,即不接受用户对此属性的任何值。我在setter上尝试了@JsonIgnore,在getter上尝试了@JsonIgnore(false),它确实忽略了它,但它也在序列化它时也这样做了。

My problem is that I want to serialize the money property but ignore while deserializing it i.e., dont accept any values from the user for this property. I have tried @JsonIgnore on setter and @JsonIgnore(false) on the getter, it does ignore it but it does so while serializing it also.

我在setter上尝试了@JsonIgnore而在getter上尝试了@JsonProperty只是为了明确告诉Jackson我们打算跟踪这个属性,这似乎会在money属性时崩溃被发送到服务器,杰克逊试图反序化它抛出MalformedJsonException:无法构造Money类型的对象。

I tried @JsonIgnore on the setter and @JsonProperty on the getter just to explicitly tell Jackson that we intend to track this property, that seems to crash the application when money property is sent to the server and Jackson tries to deserialize it throwing up MalformedJsonException : cannot construct object of type Money.

最奇怪的是,当属性是原始的时候,将@JsonIgnore放在setter上,而@JsonProperty放在setter上适用于大多数情况。

The most wierd thing is that putting @JsonIgnore on the setter and @JsonProperty on the setter works for most cases when the property is primitive.

推荐答案

好的,所以@JsonIgnore的行为从1.9开始彻底改变了(对于更糟糕的imo)。在没有深入了解为什么在反序列化期间不会忽略您的属性的恶魔细节时,请尝试使用以下代码来修复它:

Ok, so the behavior of @JsonIgnore was radically changed from 1.9 onwards (for the worse imo). Without going into the devilish details of why your property is not being ignore during deserialization, try this code to fix it:

public class UserAccount implements HasMoney {
    @JsonIgnore
    private BigDecimal money;

    // Other variable declarations, constructors

    @Override
    @JsonProperty
    public BigDecimal getMoney() {
        return money;
    }

    @JsonIgnore
    @Override
    public void setMoney(final BigDecimal money) {
        this.money = money;
    }

    // Other getters/setters
}

请注意在字段上使用 @JsonIgnore - 它是工作解决方案所必需的。

Note the use of @JsonIgnore on the field - its required for a working solution.

注意:根据您的环境和用例,您可能需要在ObjectMapper实例上进行其他配置,例如, USE_GETTERS_AS_SETTERS,AUTO_DETECT_GETTERS,AUTO_DETECT_SETTERS

Note: depending on your environment and use case, you may need additional configuration on your ObjectMapper instance, for example, USE_GETTERS_AS_SETTERS, AUTO_DETECT_GETTERS, AUTO_DETECT_SETTERS etc.

这篇关于反序列化时忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆