in Spring by
Q:

How can we use Spring to create Restful Web Service returning JSON response?

1 Answer

0 votes
by

We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.

We would need to do following steps to configure our Spring MVC application to send JSON response:

Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:

<!-- Jackson -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>${jackson.databind-version}</version>

</dependency>

Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:

<!-- 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: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>

In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:

@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)

public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {

    logger.info("Start getEmployee. ID="+empId);

     

    return empData.get(empId);

}

You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.

For a complete example, please read Spring Restful Webservice Example.

Click here to read more about Loan/Mortgage
Click here to read more about Insurance

Related questions

0 votes
asked Jul 28, 2020 in Spring by sharadyadav1986
0 votes
asked Jul 26, 2020 in Spring by SakshiSharma
0 votes
0 votes
asked Jul 28, 2020 in Spring by sharadyadav1986
0 votes
asked Dec 3, 2019 in SOAPUI by Sinaya
0 votes
asked Dec 3, 2019 in JavaScript by rajeshsharma
...