Zahid Khan Zahid Khan - 4 years ago 6898
Java Question

How to return JSON data from spring Controller using @ResponseBody

Spring version 4.2.0, Hibernate 4.1.4
Here is my Controller function.

@RequestMapping(value = "/mobile/getcomp", method = RequestMethod.GET)
@ResponseBody
public List<Company> listforCompanies() {
List<Company> listOfCompanies= new ArrayList<Company>();
listOfCompanies = companyManager.getAllCompanies();
return listOfCompanies;
}


Jackson Json mapper dependency in Pom.xml

<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>


getting the list in my arraylist but when returning the following error shown.

SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/IrApp] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList
at org.springframework.util.Assert.isTrue(Assert.java:68)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:124)


Link
of Example i am following.

Answer Source

Use Spring 4 RestController annotation as follows:

import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourController {

    @RequestMapping(value = "/mobile/getcomp", method = RequestMethod.GET)
    public List<Company>  listforCompanies() {      
        List<Company> listOfCompanies= new ArrayList<Company>();        
        listOfCompanies = companyManager.getAllCompanies();
        return listOfCompanies;
    }
}

And add below dependencies in your classpath:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download