王奕然
王奕然

Reputation: 4059

Jackson @JsonIgnore property is null

I want convert json string to one object.

The json looks like this:

{"receive":1413342268310}

And the object is like:

public class PositionBean {  
    private Long id;
    private Date receive;

    public void setReceive (Date receive) {
        this.receive = receive;
    }

    public void setReceive (Long receive) {
        this.receive = new Date (receive);
    }

    public Long getReceive () {
        return receive.getTime ();
    }
}

All the set and get methods I have to use in other class, so I can't delete one method. When I invoke

objectMapper.readValue(str, PositionBean.class);

It prompt exception, the jackon don't know which method set, so I use @JsonIgnore, but I found the receive is null.

Upvotes: 0

Views: 2043

Answers (2)

Ilya
Ilya

Reputation: 29731

You can use annotation @JsonSetter to specify which method should be used as setter.

Example:

public class PositionBean {  
    private Long id;
    private Date receive;

    public void setReceive (Date receive) {
        this.receive = receive;
    }

    @JsonSetter
    public void setReceive (Long receive) {
        this.receive = new Date (receive);
    }

    public Long getReceive () {
        return receive.getTime ();
    }
}  

When you mark setter (e.g. setXXX) with @JsonIgnore it means that property XXX will be ignored.
From documentation:

For example, a "getter" method that would otherwise denote a property (like, say, "getValue" to suggest property "value") to serialize, would be ignored and no such property would be output unless another annotation defines alternative method to use.

Upvotes: 1

SamDJava
SamDJava

Reputation: 267

You can also use

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

This will not throw any mapping exception even if u dont have an appropriate field in the mapping class corresponding to a JSON field. Once configured u can use ur code for further processing.

objectMapper.readValue (str, PositionBean.class);

Upvotes: 0

Related Questions