How to Use Spring MVC Content Negotiation to Serve JSON and XML Dynamically

This guide explains how Spring MVC can automatically negotiate response formats using the Accept header, allowing a single endpoint to return either JSON or XML based on a query parameter or MIME type, without duplicating code or routes.

Programmer DD
Programmer DD
Programmer DD
How to Use Spring MVC Content Negotiation to Serve JSON and XML Dynamically

Our service originally returned JSON to downstream systems, but a new requirement demanded XML for an older system. Instead of duplicating the interface, we can leverage Spring MVC's content negotiation mechanism.

Principle

When a client sends an HTTP request, it can include an Accept header indicating the MIME types it can handle, such as application/json. Spring MVC examines this header and selects an appropriate HttpMessageConverter to produce the response. Accept:application/json By configuring Spring MVC to recognize the Accept header, we can dynamically choose the response format.

Content Negotiation

Spring MVC provides a content negotiation mechanism where the client declares the desired MIME type, and the server returns data in that format (JSON or XML) based on configuration.

Spring MVC version based on Spring MVC 5.3.9 .

Server‑side Configuration

The negotiation is managed by ContentNegotiationManager and can be configured via ContentNegotiationConfigurer.

First, add Jackson's XML module to the project:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Then implement the configuration in a class that implements WebMvcConfigurer:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorParameter(true)
                .parameterName("format")
                .mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON);
    }
}

After this, the client can specify the desired format with a query parameter (default name format).

Request JSON:

https://yourapi?format=json
You can omit the format parameter because JSON is the default; to change the default MIME type, call defaultContentType .

Request XML: https://yourapi?format=xml The controller method only needs to declare the supported media types:

@GetMapping(value = "/get", produces = {"application/json", "application/xml"})
public Map<String, String> doGet(@RequestParam String foo, String bar) {
    Map<String, String> map = new HashMap<>();
    map.put("foo", foo);
    map.put("bar", bar);
    return map;
}

It is crucial to specify the produces attribute in @RequestMapping (or its shortcut annotations) so that Spring can select the appropriate converter.

Other Strategies

Spring MVC also supports suffix‑based negotiation (e.g., /yourapi.json or /yourapi.xml) and direct Accept header declarations, but using a query parameter is often simpler.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJSONXMLSpring MVCContent negotiation
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.