0

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.

Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
王奕然
  • 3,891
  • 6
  • 41
  • 62
  • Your best approach is probably to write a custom deserializer which converts a `long` to a `Date`. [This question](http://stackoverflow.com/questions/19158345/custom-json-deserialization-with-jackson) might be useful. (I'm sure someone has an example of this exact case out there; Jackson might even include such a mapper by default.) – Chris Hayes Oct 15 '14 at 06:28
  • Where do You use the @jsonignore? On the method? If so, could You try to do it on the receive field? – maslan Oct 15 '14 at 06:30
  • Could u update the could on where u have used JSONIgnore annotation?? – SamDJava Oct 15 '14 at 06:33
  • 1
    please refer http://stackoverflow.com/questions/10308452/how-to-convert-the-following-json-string-to-java-object – DeepInJava Oct 15 '14 at 06:36

2 Answers2

1

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.

Ilya
  • 29,135
  • 19
  • 110
  • 158
0

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);
SamDJava
  • 267
  • 3
  • 13