gpt4 book ai didi

java - 无法使用具有构建器模式的 jackson 3+ 实例化 POJO

转载 作者:行者123 更新时间:2023-11-29 03:07:52 25 4
gpt4 key购买 nike

我有以下类(class):

@JsonDeserialize(builder = Article.Builder.class)
public class Article {

private final String id;
private final String headline;

private Article(final Builder builder) {
this.id = checkNotNull(builder.id);
this.headline = checkNotNull(builder.headline);
}

@Nonnull
public String getId() {
return id;
}

@Nonnull
public String getHeadline() {
return headline;
}

public static Builder builder() {
return new Builder();
}

@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "")
public static class Builder {
private String id;
private String headline;

public Builder id(final String id) {
this.id = id;
return this;
}

public Builder headline(final String headline) {
this.headline = headline;
return this;
}

public Article build() {
return new Article(this);
}
}

}

通过这些注解,我可以使用 Jackson ObjectMapper 序列化和反序列化对象,但是在以下 Controller 中使用 Article 时我收到错误消息:

@RequestMapping(value = "/article/{category}", method = PUT)
public void receiveArticle(@PathVariable("category") final String category, final Article article) {
service.createOrUpdateArticle(category, article);
}

用这个 URL 调用它:

http://localhost:8080/article/cat_1/?article={"id":"aid001","headline":"this is the headline"}

这是错误:

HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.Article]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.example.Article.<init>()

java.lang.NoSuchMethodException: com.example.Article.<init>()
java.lang.Class.getConstructor0(Class.java:2892)
...

我按照本教程使用了构建器模式:http://wiki.fasterxml.com/JacksonFeatureBuilderPattern

有人知道为什么我会收到此错误吗?

最佳答案

Spring 不会使用 JSON 反序列化为您的处理程序方法生成参数。

@RequestMapping(value = "/article/{category}", method = PUT)
public void receiveArticle(@PathVariable("category") final String category, final Article article) {
service.createOrUpdateArticle(category, article);
}

按照您当前的方式,Article 参数被解释为模型属性,就像用 @ModelAttribute 注释一样。 Spring 将尝试使用无参数构造函数来实例化该类。由于您的 Article 类没有提供,因此它失败了。

相反,将 JSON 移动到请求的正文中,在请求中发送 Content-Type: application/json header ,并使用 @RequestBody 注释您的参数.

@RequestMapping(value = "/article/{category}", method = PUT)
public void receiveArticle(@PathVariable("category") final String category, @RequestBody final Article article) {
service.createOrUpdateArticle(category, article);
}

关于java - 无法使用具有构建器模式的 jackson 3+ 实例化 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31141945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com