因为使用Result类封装返回的数据,但是发送请求之后终端一直报
WARN Could not find acceptable representation
前端显示406,百度两天无果
"status": 406,
"error": "Not Acceptable",
然后开始逐一排错,测试类里面挨个测试了Mapper跟ServiceImpl,返回结果均是正常的
后来把矛头指向了Controller层,但是Debug的流程没有一点问题,但是返回结果是个Result
有点不解,我的请求层是这样的
@RestController
@RequestMapping("/people")
public class PeopleController{
``
@Autowired
PeopleService peopleService;
@GetMapping
public Result selectAll() {
List<People> people = peopleService.getAll();
return new Result(people);
}
}
我的Result类是这样的
public class Result{
public final static String Succeed_Code="200";
public final static String Fail_Code="400";
private String code;
private String msg;
private Object data;
public Result(Object data) {
this.code = Succeed_Code;
this.data=data;
}
}
百度给出的解决方案就是因为我Controller层用了@RestController注解,但是返回结果不是JSON,我尝试在pom里面加上fastjson,后面发现其实Spring MVC的依赖里已经包含了一个JSON的依赖
经过一天多的摸索,终于找到了解决方案
Result类修改如下
@Data
public class Result{
public final static String Succeed_Code="200";
public final static String Fail_Code="400";
private String code;
private String msg;
private Object data;
public static Result success(Object data){
Result result = new Result();
result.setCode(Succeed_Code);
result.setData(data);
result.setMsg("操作成功");
return result;
}
}
Controller修改如下
@RestController
@RequestMapping("/people")
public class PeopleController{
@Autowired
PeopleService peopleService;
@GetMapping
public Result selectAll() {
List<People> people = peopleService.getAll();
return Result.success(people);
}
}
不是很理解为什么这样会出错