如何使用@ResponseBody从spring Controller返回JSON数据

2022-08-31 16:13:19

春季版 4.2.0,休眠 4.1.4这是我的函数:Controller

@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>

在 my 中获取列表,但在返回时显示以下错误:ArrayList

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)

链接到我遵循的示例。


答案 1

我遇到了同样的问题。我没有把,因为我正在使用.但是我仍然遇到错误,因为我没有为公司类放置方法。所以在把后我的问题解决了。@ResponseBody@RestControllergetter/settergetter/setter


答案 2

将以下依赖项添加到您的 pom.xml:

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