我想将 json 字符串转换为一个对象。
json 看起来像这样:
{"receive":1413342268310}
该对象如下:
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 ();
}
}
我必须在其他类中使用所有 set 和 get 方法,因此我无法删除其中一个方法。 当我调用时
objectMapper.readValue(str, PositionBean.class);
提示异常,jackon不知道设置了哪个方法,所以我使用@JsonIgnore,但是我发现receive是null。
最佳答案
您可以使用注释@JsonSetter指定应使用哪个方法作为 setter。
示例:
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 ();
}
}
当您使用 @JsonIgnore 标记 setter(例如 setXXX)时这意味着属性 XXX 将被忽略。
来自文档:
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.
关于java - jackson @JsonIgnore 属性为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375658/