Spring Boot Rest API — JSON and XML Responces | Code Factory

Reference Link : Link

Donate : Link

pom.xml

application.properties

SpringBootRestJsonXmlApplication.java

RestController.java

Employee.java

http://localhost:8080/loginPage without authentication

http://localhost:8080/loginPage with authentication

In Mapping use produces="application/xml" or produces="application/json" for XML or JSON response

pass above _csrf tocken in Body

What if you don’t want to use produces property of Mapping, then how will you receive XML or JSON response?

Answer is, use header while calling any method. Give Key as “Accept” and values as “application/json” if you need JSON response and “application/xml” for Xml response. In this way we can get both json and xml responses from a single method.

Method :
@PostMapping(value="/getData")
public Employee getData(HttpServletRequest request) {
return new Employee("EMP_ID", "EMP_NAME");
}

XML response :

JSON response :

Note : Don’t forgot to pass _csrf tocken in http://localhost:8080/getData URL

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store