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.

To make your Web Service endpoint be able to respond with either XML or JSON representation include  MediaType.APPLICATION_JSON_VALUE  and MediaType.APPLICATION_XML_VALUE media types into the RequestMapping annotation of your resource method. For example:

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

or for HTTP Post request:

@PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )

or for HTTP Put request:

@PutMapping(path="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )

You get the idea.

@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 which 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 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 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 :).