我有一个使用 Spring Boot 提供 REST 功能的应用程序。我在将 POST 响应反序列化为 POJO 时遇到问题。例外情况如下:
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [collection type; class uci.BoundedList, contains [simple type, class java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `uci.BoundedList` (no Creators, like default construct, exist): no default no-arguments constructor found
The BoundedList
type 是使用 XJC 从 XML 模式生成的 API 的一部分。我无法控制这个类是如何生成的。事实证明它是一个子类java.util.ArrayList
并且只定义了一个构造函数:
public BoundedList(int minOccurs, int maxOccurs) {
super();
this.minOccurs = minOccurs;
this.maxOccurs = maxOccurs;
}
它没有定义无参数构造函数,这就是异常似乎抱怨的内容。
由于我无法修改此类,并且它是我正在使用的 API 的一个组成部分,那么我该怎么做才能解决这个问题呢?我可以提供某种定制的类/接口来满足 Jackson 数据绑定吗?还有其他可能的解决方案吗?
UPDATE:
我根据下面提供的答案尝试了一些建议。它们都不起作用。我正在研究“混合”方法,我承认我不太明白它应该如何工作。我看过的很多文章写得虽然简单,但似乎还是有点“黑魔法”。
无论如何,下面是我根据所读内容尝试做的事情的片段:
“混合”类:
public abstract class BoundedListMixin {
@JsonCreator
public BoundedListMixin(@JsonProperty("minOccurs") int minOccurs,
@JsonProperty("maxOccurs") int maxOccurs) {}
}
添加到现有配置类中的内容:
@Configuration
@EnableAsync
@EnableScheduling
@ComponentScan("<package>")
public class ServiceConfigurer {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.createXmlMapper(false).build();
mapper.addMixIn(BoundedList.class, BoundedListMixin.class);
return mapper;
}
}
我可以确认objectMapper()
通过调试器调用配置类中的方法。
这个链接(https://dzone.com/articles/jackson-mixin-to-the-rescue https://dzone.com/articles/jackson-mixin-to-the-rescue)引入了另一个方面,但遗憾的是,这也不起作用。
UPDATE:
我已经更换了objectMapper()
中的方法ServiceConfigurer
(上)具有以下内容:
@Bean
public Jackson2ObjectMapperBuilderCustomizer objectMapperCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.mixIn(BoundedList.class, BoundedListMixin.class);
}
};
}
我仍然遇到同样的问题。该问题必须与其他问题相关。
NOTE:
我还应该澄清,当我做了一个GET
称呼。我有一个简单的 REST 端点,它只请求服务返回 POJO。奇怪的是,如果我从浏览器发送请求,对象将以 JSON 形式返回并呈现。但是,当从代码中调用它时,我得到了上面的异常。
GET 调用:
RequestStatus statusMsg = template.getForObject("http://localhost:8080/rst/missionPlanning/data", RequestStatus.class);