Spring Boot:关于“No converter found for return value of type: class xxx”的解决方法

Spring Boot:关于“No converter found for return value of type: class xxx”的解决方法

(提示:本文的解决方法仅限本文上下文情况)

默认你在@RestController下返回的java对象(如下User)是没有问题的

// controller
@RestController
public class ZezeController {
    @RequestMapping("/zezeze")
    public User zeze() {
        return new User("xyz", 24);
    }
}
// domain
public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

但就是出现“No converter found for return value of type: class xxx”的错误信息说什么对象不能成JSON,
然后在网上找了一些解决方案,给项目添加了jackson依赖的全家桶,

// 注:如下依赖不能解决本文情况
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.7'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.7'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.7'

然而还是照常报错提示。按理说 Spring Boot应该在@RestConroller下自动将对象转换成JSON返回的,而且很多情况下都不用弄什么第三方来辅助的,@#¥%……&*(此处吐槽一万字)

不卖关子了,解决方案很简单:
Spring Boot:关于“No converter found for return value of type: class xxx”的解决方法
只要你给返回的对象(如本文所示的User)的private属性添加几个getter(、setter)方法就OK了,不至于在IDE上显示属性为never accessed之类就行。
Spring Boot:关于“No converter found for return value of type: class xxx”的解决方法
修改后就返回预期的结果:
Spring Boot:关于“No converter found for return value of type: class xxx”的解决方法