gpt4 book ai didi

java - 如何将 Spring MVC 的默认媒体类型从 XML 更改为 JSON

转载 作者:行者123 更新时间:2023-11-29 04:01:02 25 4
gpt4 key购买 nike

标题几乎说明了一切。现在它在我的 Controller 的响应中使用 XML 作为默认值,但我希望它在未指定 Accepts header 或格式参数时使用 JSON 作为默认值。

我的mvc-config.xml

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">

<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="com.work.web.view.json.ExtendedMappingJacksonJsonView">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<ref bean="Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
<property name="favorParameter" value="true" />
</bean>

<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<ref bean="marshallingHttpMessageConverter" />
</list>
</property>
</bean>

<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="Jaxb2Marshaller" />
<property name="unmarshaller" ref="Jaxb2Marshaller" />
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="JacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="JacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="JacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
<bean id="Jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.work.Concepts</value>

</list>
</property>
</bean>

最佳答案

<property name="defaultContentType" value="application/json" />

设置 ContentNegotiatingViewResolver bean 时

关于java - 如何将 Spring MVC 的默认媒体类型从 XML 更改为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3620323/

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