Tutorial

Spring REST XML and JSON Example

Published on August 3, 2022
Default avatar

By Pankaj

Spring REST XML and JSON Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Spring Restful Web Services XML and JSON example. Sometime back I wrote an article about Spring REST JSON and I got a lot of comments asking how to change the program to support XML. I got some emails also asking how to make application supports both XML as well as JSON.

Spring REST XML and JSON

I thought to write an article about Spring REST XML and JSON application where I will show you how easily we can extend the existing application to support XML. Since I will be making changes to the existing project, make sure you first download it from below link.

Download Spring Restful Webservice Project

Now do following changes to spring bean configuration file.

  1. Define a bean of type Jaxb2RootElementHttpMessageConverter.

    <beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
    </beans:bean>
    
  2. Add above configured bean to RequestMappingHandlerAdapter property messageConverters.

    <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
    	<beans:list>
    		<beans:ref bean="jsonMessageConverter"/>
    		<beans:ref bean="xmlMessageConverter"/>
    	</beans:list>
    </beans:property>
    </beans:bean>
    

After above changes, our final spring bean configuration file will look like below. servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- Configure to plugin JSON as request and response in method handler -->
	<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<beans:property name="messageConverters">
			<beans:list>
				<beans:ref bean="jsonMessageConverter"/>
				<beans:ref bean="xmlMessageConverter"/>
			</beans:list>
		</beans:property>
	</beans:bean>
	
	<!-- Configure bean to convert JSON to POJO and vice versa -->
	<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
	</beans:bean>	
	
	<beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
	</beans:bean>
	
	<context:component-scan base-package="com.journaldev.spring.controller" />
	
</beans:beans>

We know that for working with JAXB marshalling for a class, we need to annotate it with @XmlRootElement annotation. So add this to our Employee model class. Employee.java

@XmlRootElement
public class Employee implements Serializable{

//no change in code
}

That’s it, we are DONE. Our Spring application will support both JSON as well as XML. It will even support XML request with JSON response and vice versa. Below are some of the screenshots showing this in action. NOTE: I am using Postman Chrome application for this, you can use any rest client for this testing. 1. XML Response: Make sure you pass Accept header as “application/xml”. spring xml, spring rest xml 2. JSON Response: Make sure you pass Accept header as “application/json”. spring json, spring rest json 3. XML Request with JSON Response: Make sure Accept header is “application/json” and Content-Type header is “text/xml” as shown in below images. spring rest xml json, spring restful web services spring restful web services That’s all for Spring Restful web services example for supporting both XML and JSON. You can see how easy it is to extend Spring framework, this is one of the major reason of spring framework popularity.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 28, 2018

my 404 issue reslove form web.xml following changes dispatcher /

- jk

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 28, 2018

    2018-08-28 10:00:48,330 [localhost-startStop-1] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed what is that error???

    - sumit

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 31, 2018

      Hi Pankaj, How to write Rest Client Program for the same like your previous example for all combination like xml to xml, xml to json, json to xml? Thanks in advance!

      - Priyanka

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 18, 2018

        thanks

        - arun singh

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 5, 2018

          Hello Pankaj I have tried your its fantastic . its very useful when have hardcoded data,but if we want this same thing with service and dao how can we achieve this?? because when ever we bring data from db , we must have to bring from employee class or table. but for xml we have to make another class EmployeeList class in which we contain employee as list. but how can I return list from employee class if I put EmployeeList as method return type. everytime m doing that in service its showing that unable convert from Employee to EmployeeList,hopw can I resolve this? how can I put that list of employees to EmployeeList and return EmployeeList…

          - J Manas Kumar

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 12, 2018

            Hello Pankaj as u referred me this i have check this, but the thing is that when i am going to create an employee its throwing error in postman and i am unable to see any specific error in console , so there are no eror in console. Can you help me to resolve this issue?? Please…

            - J Manas Kumar

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 20, 2017

              Thanks for ALL :) All your article are simple and easy to understand, to me they very structured et well done. You’re the best :)

              - Badr C

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 28, 2016

                Sir thanks for the posting this working example but . I am getting only json string as response not the xml reesponse

                - sachin sarwadnya

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  February 22, 2016

                  I want list of employees in xml while it comes in JSON list

                  - rahul

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 15, 2015

                    I am also getting only xml form of response only. how could I get in both the formats.

                    - sandeep

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel