Return XML or JSON in Spring Boot Web Service

This tutorial will teach you how to make your RESTful Spring Boot API endpoint respond with either XML or JSON representation.

The client application can request our API endpoint to respond with JSON or XML by including a special HTTP Header called Accept. As a value, the Accept HTTP Header will have either application/json or application/xml. 

Below is an example of an HTTP request prepared in Postman HTTP Client. Notice the value of the Accept HTTP Header.

Accept HTTP Header

Sending JSON in HTTP Response

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

produces = MediaType.APPLICATION_JSON_VALUE

Let’s have a look at a couple of examples.

Respond with JSON to a GET request

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

Respond with JSON to POST request

@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE )

In this case, our web service endpoint will always respond with a JSON representation of a resource. Even if the Accept HTTP header is not provided.

Note: If your Spring Boot application has no XML support configured, you can skip the MediaType.APPLICATION_JSON_VALUE and your web service endpoint will respond with JSON representation by default.

Sending XML in HTTP Response

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 able to respond 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 with XML representation only, configure a single MediaType.APPLICATION_XML_VALUE. 

produces = MediaType.APPLICATION_XML_VALUE

Let’s have a look at a couple of examples.

Respond with XML to a GET request

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

Respond with XML to a POST request

@PostMapping(produces = MediaType.APPLICATION_XML_VALUE )

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

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

Respond with Either JSON and XML Representation

To make our application able to produce both XML and JSON representation, we will need to either remove produces completely or add 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 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 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 than one MediaType, then their order matters. If the client application does not include the Accept HTTP header in the request, our web service will respond with a Resource using the Representation 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, my web service endpoint will respond with XML representation.

What If No Accept HTTP Header is Provided?

By default, if no Accept HTTP Header is provided and no 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 demonstration purposes and do not do much other than demonstrating the request mapping annotation and how to enable XML or JSON representation response 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 the user details 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 Boot and enable your Web Service endpoints to respond 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 this short Spring Boot tutorial on enabling your RESTful Web Service endpoints to return XML or JSON representation was helpful. If you have any questions, please comment below.

If you are interested in learning more about Spring Boot, check out other tutorials on building 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 *