by BehindJava

How to return object as XML or JSON representation using Produces in Spring Boot

Home » springboot » How to return object as XML or JSON representation using Produces in Spring Boot

In this tutorial we are going to learn about Produces that make the object representation as XML or JSON as per the requirement.

Firstly, go to the postman, under headers update the key value pairs as per your requirement i.e. in this case I want my object representation as XML so I updated key and value following, KEY: Accept and VALUE: application/xml.

title

To support the XML representation of the object we need to add a dependency else we will run through error code 406.

In the Maven repository you can find the dependency named Jackson DataFormat XML.

Inside the pom.xml you can add this dependency as show in the image.

title

Produces narrows the primary mapping by media types that can be produced by the mapped handler.

Consists of one or more media types one of which must be chosen via content negotiation against the “acceptable” media types of the request.

Typically, those are extracted from the “Accept” header but may be derived from query parameters, or other.
Examples:
produces = “text/plain”
produces = {“text/plain”, “application/*“}
produces = MediaType.TEXTPLAINVALUE
produces = “text/plain;charset=UTF-8”

If a declared media type contains a parameter (e.g. “charset=UTF-8”, “type=feed”, “type=entry”) and if a compatible media type from the request has that parameter too, then the parameter values must match. Otherwise if the media type from the request does not contain the parameter, it is assumed the client accepts any value.

Expressions can be negated by using the ”!” operator, as in “!text/plain”, which matches all requests with a Accept other than “text/plain”.

Supported at the type level as well as at the method level! If specified at both levels, the method level produces condition overrides the type level condition.

Sample Code Snippet:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.behindjava.tutorial.model.UserModel;

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

	@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, 
    MediaType.APPLICATION_JSON_VALUE })
	public UserModel getUser(@PathVariable String userId) {
		UserModel um = new UserModel();
		um.setFirstname("Lakshmi Deepak");
		um.setLastname("Chella");
		um.setUserId("cl001");
		um.setEmail("[email protected]");
		return um;
	}
}

In the similar way we can use consumes to make our get user method accept the XML or JSON payload.

Previous                                                                                                               Next