No converter found for return value of type: class XXX.XXX....
网上很多的解决办法,添加依赖,写配置类啥的,都不管用,这里记录一下
出现这种问题的主要原因就是在controller中使用的是@Restcontroller,想要返回的是JSON类型的数据,但是返回的数据没办法转换成JSON,话不多说,上例子:
首先我定义一个Result的类,主要是想用Result.ok的方式,直接返回JSON数据给前台
public class Result implements Serializable { private String status; private String msg; private Object data; public static Result buildResult(String status, String msg, Object data){ return new Result(status,msg,data); } public static Result ok(Object data){ return new Result(data); } public Result(String status,String msg,Object data){ this.data = data; this.msg = msg; this.status = status; } public Result(Object data){ this.data = data; } }
然后我的controller文件是这样的
@RestController public class TestController { @Autowired TestMapper testMapper; @GetMapping(value = "/test") public Result test(){ Map<String,String> map = new ConcurrentHashMap<>(); map.put("test","test"); map.put("test1","test2"); map.put("test2", String.valueOf(testMapper.getTest())); return Result.ok(map); } }
然后在页面访问这个地址报500,查看后台控制台,有如下内容
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.electric.datacenter.entity.Result]
不废话,直接上解决办法,就是添加getter,setter的方法就可以了,如下
public class Result implements Serializable { private String status; private String msg; private Object data; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public static Result buildResult(String status, String msg, Object data){ return new Result(status,msg,data); } public static Result ok(Object data){ return new Result(data); } public Result(String status,String msg,Object data){ this.data=data; this.msg=msg; this.status=status; } public Result(Object data){ this.data=data; } }