gpt4 book ai didi

json - 我希望我的 controlleradvice 在处理异常时总是产生 JSON

转载 作者:行者123 更新时间:2023-12-01 05:09:52 26 4
gpt4 key购买 nike

我已将我的休息服务的异常处理集中到一个整洁的 ControllerAdvice 中。

我正在返回常规传输对象,希望我很酷的 mapping-jackson-converter 将它转换为最终客户端的 JSON。

现在事情来了。如果我不将接受 header 设置为“应用程序/JSON”,我就不会得到转换后的 JSON,而是得到一些默认的 HTML,在我的测试中似乎是由 Jetty 生成的。我不得不承认我不知道为什么,但我想这是一些默认的 Spring 解析器生效。

这让我思考。调用我的其余 URL 的客户应该知道我返回 JSON,所以我希望我的服务始终返回 json。

有什么方法可以配置 ReqeustMappingHandlerAdapter 以始终生成 JSON?

我目前的配置:



<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonConverter"/>
</beans:list>
</beans:property>
</beans:bean>

<!-- Instantiation of the converter in order to configure it -->
<beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<!--beans:property name="supportedMediaTypes" value="application/json"/-->
</beans:bean>

最佳答案

我不知道这是否能回答您的问题,但您可以将 Spring 配置中的默认内容类型设置为 JSON(它默认为 HTML,在 Spring MVC 中没有 Accept header )。这是一个示例配置:

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
</bean>

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

来源:

http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

关于json - 我希望我的 controlleradvice 在处理异常时总是产生 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25774503/

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