Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

java - Ignoring property when deserializing

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

public interface HasMoney { 

      Money getMoney();

      void setMoney(Money money);

 }

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

}

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.

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.

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.

question from:https://stackoverflow.com/questions/16019834/ignoring-property-when-deserializing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...