How to return JSON data from spring Controller using @ResponseBody

Zahid Khan picture Zahid Khan · Oct 2, 2015 · Viewed 107.3k times · Source

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 is 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 to the example I'm following.

Answer

Arpit Aggarwal picture Arpit Aggarwal · Oct 2, 2015

Add the below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>