I have gone through other similar asked questions but nothing worked for me.
All my API's return JSON as response by Default:
Because of some XML API, i had to add jackson-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Now by default "Without accept header" All responses are XML.
I would like to have JSON as default Response format .
As stated in the doc here:
https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
I implemented the following config :
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true)
.useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
}
Case 1: if i make the ignoreAcceptHeader(true)
then everything is JSON even the XML API returning JSON.
Case 2: when ignoreAcceptHeader(false)
is then default is XML.
I forget to mention my API's look like this:
@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
throws JAXBException {
return returnXml();
}
I am quite lost here, All i want is Default(Without AcceptHeader) should be JSON. (API returns XML as String)
And when Accept Header : "Application/xml" is defined then response should be XML.
Any advice would be of great help.
Thanks.
Now by default "Without accept header" All responses are XML.
To add the extension, add the following dependency in the project build. After adding the above dependency and updating the project, the Jackson XML extension will get added in the classpath so the Spring MVC will automatically pick this up for XML responses. Example: XML.
In general if you want to get json response you need an jackson-databind module:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${json-jackson-version}</version>
</dependency>
and then you have to define a MappingJackson2HttpMessageConverter
in your configuration:
@Configuration
@EnableWebMvc
public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
[..]
super.configureMessageConverters(converters);
}
[...]
}
In your case, you can implement your own AbstractGenericHttpMessageConverter so you can switch in this converter between different concrete converters depending on media type.
Check the method AbstractGenericHttpMessageConverter#writeInternal(..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With