Return XML or JSON in Spring MVC Web Service

In this Spring MVC tutorial, you will learn how to make your RESTful Web Service endpoint respond back with either XML or JSON representation.

When the client application sends a request to our web service to get a Resource, like for example, User Details, it can provide a special HTTP Header that will request our web service to respond back with either JSON or XML. This special HTTP Header is called Accept. And then as a value, it will have either application/json or application/xml for example.

Accept HTTP Header

Respond with JSON Only

By default, our web service endpoint will respond back with JSON representation. To enforce our web service endpoint to always respond back with JSON representation of a resource, we can add a single media type to a request mapping annotation.

For example:

@GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)

or for HTTP Post request:

@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE )

In this case, whether the client application provides Accept HTTP header or not, out web service endpoint will always respond back with JSON representation of a resource.

Note: If your Spring Boot project, does not have any XML support configured, then you can skip the MediaType.APPLICATION_JSON_VALUE and your web service endpoint will respond back with JSON representation by default. But if you do not provide the MediaType.APPLICATION_JSON_VALUE and later and an XML support dependency to a pom.xml. Then, if a client application provides Accept HTTP header with a value application/xml, then your web service endpoint will respond back with XML representation.

If you want to enforce your web service endpoint to always respond back with JSON representation only, provide a single MediaType.APPLICATION_JSON_VALUE. 

Respond with XML Only

To make our web service application respond back with XML representation only, even if the Accept HTTP Header is not provided, we will need to add a new dependency to the pom.xml file to support XML and explicitly specify that our web service endpoint produces XML representation only.

Add XML Support Dependency to POM.XML

To make your RESTful web service endpoints be able to respond back with the XML representation of a resource, you need to add the following dependency to the POM.XML file of your Spring Boot project.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Add Application XML Media Type

To make your web service endpoint respond back with XML representation only, configure a single MediaType.APPLICATION_XML_VALUE. 

For example:

@GetMapping(path = "/{id}", produces = MediaType.APPLICATION_XML_VALUE)

or for HTTP Post request:

@PostMapping(produces = MediaType.APPLICATION_XML_VALUE )

In this case, whether the client application provides Accept HTTP header or not, out web service endpoint will always respond back with the XML representation of a resource.

Below is an example of how to add Accept HTTP Header with application/xml value in Postman HTTP Client.

Respond with Either JSON and XML Representation

To make our application be able to produce both XML and JSON representation, we will need to either remove produces completely, or add to it both the MediaType.APPLICATION_JSON_VALUE and the MediaType.APPLICATION_XML_VALUE media types.

produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }

Note: In this case we will need to surround media type values with the curly brackets.

In this case, to request XML representation of a resource, the client application will need to provide the Accept HTTP header with a value application/xml, and to request JSON representation of a resource the client application will need to provide Accept HTTP header with a value application/json.

To make your web service be able to respond with XML representation, you will need to add the following dependency to POM.xml file of your Spring Boot project.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

The Order Matters

Now when we have configured our web service endpoint to be able to respond with either XML or JSON, what would be the default representation if the client application does not include the Accept HTTP header in the response?

If we do not provide any of these media types, then the default representation of a resource will be JSON. But if we have configured more that one MediaType, then their order matters, and if the client application does not include the Accept HTTP header in the request, then our web service will respond back with a Resource using the Representation that is configured first in the list of media types. In my case the first media type is XML, so if no accept HTTP header is provided, then my web service endpoint will respond back with XML representation.

What If No Accept HTTP Header is Provided?

By default, if no Accept HTTP Header is provided and not supporting media types are configured, our web service endpoint will respond back with a JSON representation of a resource.

To make your RESTful Web Service endpoint respond back with JSON representation by default, simply do not provide any supported media types in the request mapping annotation.

@RestController Class – Enable XML or JSON Representation Response

Let’s look at how the MediaType.APPLICATION_JSON_VALUE  and MediaType.APPLICATION_XML_VALUE are used in a @RestController class with methods mapped to HTTP Requests. All methods in the below class are just for a demonstration purpose and do not do much other than demonstrating the request mapping annotation and how to enable XML or JSON representation response by using the MediaType.APPLICATION_JSON_VALUE and MediaType.APPLICATION_XML_VALUE.

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;
 
    @GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public UserRest getUser(@PathVariable String id) {

        UserRest returnValue = new UserRest();
           
        // Some code here...
 
        return returnValue;
    }

    @GetMapping(
            produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} 
    )
    public List<UserRest> getUsers(@RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "limit", defaultValue = "30") int limit) {
        List<UserRest> returnValue = new ArrayList<>();
      
       // Some code here...

        return returnValue;
    }

    @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )
    public UserRest createUser(@RequestBody UserDetailsRequestModel requestUserDetails) {
        UserRest returnValue = new UserRest();
                
       // Some code here...

        return returnValue;
    }
 
    @PutMapping(path="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )
    public UserRest updateUser(@PathVariable String userId, @RequestBody UserDetailsRequestModel requestUserDetails) {
        UserRest returnValue = new UserRest();
 
        // Some code here...

        return returnValue;
    }

}

You might have noticed that all the methods in the example above return the UserRest object. In your application, it most likely going to be a different class. The UserRest in my application represents user details and it is a class that will be converted into XML or JSON representation. Below is the source code of my UserRest java class:

package com.appsdeveloperblog.app.ws.ui.model.response;

public class UserRest {

    private String userId;
    private String firstName;
    private String lastName;
    private String email;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String publicId) {
        this.userId = publicId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

POM.XML Dependencies

You might also double-check that your pom.xml file contains the following dependencies which provide support for building RESTful Web Services with Spring MVC and enable your Web Service endpoints response with XML or JSON representation.

 <dependencies>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

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

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>

</dependencies>

A Video Tutorial

 

And this is it! I hope that this short Spring MVC tutorial on how to enable your RESTful Web Service endpoints to return XML or JSON representation was helpful. If you have any questions, please comment below. Explore my blog to find even more tutorials on how to build RESTful Web Service with Spring MVC or Jersey JAX-RS.

If you are like me and like learning by watching step by step video lessons then check out a list of video courses below. Learning by watching step by step video lessons is much better and faster than trying to find code examples piece by piece on the Internet :).


Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!