gpt4 book ai didi

spring-boot - 返回 Resources 或 PagedResources 结果时,Spring HATEOAS (w Spring Boot) JAXB 编码错误

转载 作者:行者123 更新时间:2023-12-04 19:06:18 33 4
gpt4 key购买 nike

我的 Controller 中有这样的东西:

@RequestMapping
@ResponseBody
public HttpEntity<PagedResources<PromotionResource>> promotions(
@PageableDefault(size = RestAPIConfig.DEFAULT_PAGE_SIZE, page = 0) Pageable pageable,
PagedResourcesAssembler<Promotion> assembler
){

PagedResources<PromotionResource> r = assembler.toResource(this.promoService.find(pageable), this.promoAssembler);

return new ResponseEntity<PagedResources<PromotionResource>>(r, HttpStatus.OK);
}

如果我导航到映射到该 Controller 方法的 URL,我会收到 500 错误,其根本原因是:
com.sun.istack.internal.SAXException2: unable to marshal type "commerce.api.rest.resources.PromotionResource " as an element because it is missing an @XmlRootElement annotation 

如果我在我的资源上抛出一个 @XmlRootElement 注释,它就会变成这个错误:
com.sun.istack.internal.SAXException2: unable to marshal type "commerce.api.rest.resources.PromotionResource " as an element because it is not known to this context.

如果接受 header 是 application/json 或 application/hal+json,一切都很好。仅当客户端(在本例中为 chrome)正在查找 application/xml 时才会导致问题(这很有意义,因为 HATEOAS 正在遵循客户端请求。我正在使用 Spring Boot 的 @EnableAutoConfiguration,它将 XML 消息转换器添加到列表中从而启用 XML 内容类型。

我猜我至少有两个选择:
1.修复jaxb错误
2. 删除 xml 作为支持的内容类型

不知道该怎么做,或者也许还有另一种选择。

最佳答案

如果您实际上不想生成 XML,请尝试使用 produces @RequestMapping 的属性注解。类似:@RequestMapping(produces=MediaType.APPLICATION_JSON_VALUE)
或者,您可以排除 jaxb从您的类路径或查看添加您自己的 org.springframework.boot.autoconfigure.web.HttpMessageConverters bean 完全控制注册的 HttpMessageConverter的。见 WebMvcConfigurationSupport.addDefaultHttpMessageConverters查看默认情况下 Spring 将添加的内容。

关于spring-boot - 返回 Resources<T> 或 PagedResources<T> 结果时,Spring HATEOAS (w Spring Boot) JAXB 编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480517/

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