由IDEA构建的SpringMVC:找不到类型返回值的转换器

我使用IDEA基于SpringMVC搭建了一个简单的RESTful服务器。但是@RestController 和@ResponseBody 无法通过jackson JSON 将POJO 转换为JSON。


在dispatcher-servlet.xml 中:


<mvc:annotation-driven/>

在pom.xml 中:


    <dependency>

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

        <artifactId>jackson-annotations</artifactId>

        <version>2.9.5</version>

    </dependency>

    <dependency>

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

        <artifactId>jackson-core</artifactId>

        <version>2.9.5</version>

    </dependency>

    <dependency>

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

        <artifactId>jackson-databind</artifactId>

        <version>2.9.5</version>

    </dependency>

我的控制器:


@RestController

@RequestMapping("/test")

public class TestController {


    @GetMapping("/one")

    public One getOne() {

        return new One(1);

    }

}

我的POJO:


public class One {

    public One(int number) {

        this.number = number;

    }


    public int getNumber() {

        return number;

    }


    public void setNumber(int number) {

        this.number = number;

    }


    private int number;

}


但我仍然得到No converter found for return value of type error 。我不知道为什么。我遇到了一些配置或其他东西吗?


汪汪一只猫
浏览 380回答 2
2回答

眼眸繁星

您需要指定生产/消费来定义您想要的数据类型,例如:@RestController@RequestMapping("/test", produces = {MediaType.APPLICATION_JSON_VALUE})public class TestController {&nbsp; &nbsp; @GetMapping("/one")&nbsp; &nbsp; public One getOne() {&nbsp; &nbsp; &nbsp; &nbsp; return new One(1);&nbsp; &nbsp; }}

达令说

试着把它放在你的 dispatcher-servlet.xml 中:<mvc:annotation-driven>&nbsp; &nbsp; &nbsp;<mvc:message-converters>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>&nbsp; &nbsp;</mvc:message-converters></mvc:annotation-driven>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java