【问题标题】:Constructor annotated with Jackson @JsonCreator not being called in POJO?没有在 POJO 中调用带有 Jackson @JsonCreator 注释的构造函数?
【发布时间】:2016-09-04 04:56:34
【问题描述】:

我正在使用将 POJO 存储在 MongoDB 中的 Web 服务。我想利用 Mongo 的 'expireAfterSeconds' 生存时间功能,在一段时间后清除我收藏中的旧文档。

最初我有一个使用以下 JSON 将日期发送到 REST 服务的实现:

{ "testIndex": "testIndex", "name": "hello", "date": "2016-05-09T11:00:39.639Z" }

上面的代码在集合中创建了文档,加上下面的注解,10秒后删除了文档。

@Indexed (expireAfterSeconds=10)
private Date date;

实现此代码后,我决定只在 Java 端生成日期,这意味着 JSON 现在如下:

{ "testIndex": "testIndex", "name": "hello" }

然后我在 POJO 中有一个使用 Jackson 的 JsonCreator 的构造函数

@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
    this.testIndex = testIndex;
    this.createdAt = new Date();
    this.name = name;
}

通过阅读文档here,我相信这应该标记在创建新对象时要使用的构造函数。 testIndex 和 name 字段像以前一样填充。然而,通过这个实现,每次我在我的 mongo 中检查文档时,日期值都是“null”。如果我将其中一个字符串值的文本更改为“来自构造函数的你好”,构造函数似乎不会被调用,因为 JSON 中包含的初始文本是添加到数据库中的内容。

POJO

`

@Document(collection = "test")public class TTLTestVO {

@Id private String _id;

@Indexed
private String testIndex;

@Indexed (expireAfterSeconds=10)
private Date createdAt;

private String name;

@JsonIgnore
public TTLTestVO() {
    // default
}

@JsonCreator
public TTLTestVO (@JsonProperty("testIndex") String testIndex, @JsonProperty("name") String name) {
    this.testIndex = "hello from the constructor";
    this.name = name;
}

public String getId() {
    return _id;
}

public void setId(String _id) {
    this._id = _id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getTestIndex() {
    return testIndex;
}

public void setTestIndex(String testIndex) {
    this.testIndex = testIndex;
}

public Date getDate() {
    return createdAt;
}

public void setDate(Date date) {
    this.createdAt = date;
}
`

【问题讨论】:

    标签: java json mongodb jackson


    【解决方案1】:

    在调查了更多之后,我发现问题在于 @JsonCreator 的 Spring Framework 实现 - 我删除了 org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.annotation 的导入并将它们替换为 com.fasterxml.jackson.annotation。上述实现现在按预期运行。

    我一直无法在网上找到关于为什么春季版本不起作用的解释,所以如果有人有任何想法,请让我/其他人知道

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2019-10-16
      • 2017-04-26
      相关资源
      最近更新 更多