问题描述
1.使用Postman测试写的接口时,发现错误,请求可以接收,但是参数为空,
@RestController @RequestMapping("tsetApi") public class CompareController { @PostMapping("query1") public String getTestPost1(@RequestParam(name="id",required = false) String id, @RequestParam(name="name",required = false) String name){ System.out.println(id+name); return "1"; } @PostMapping("query2") public String getTestPost2(@RequestBody UserInfo userInfo){ System.out.println(userInfo.toString()); return "1"; } @Data public class UserInfo { private String id; private String name; } }
调用第一个接口,请求成功,始终拿不到值,Postman请求参数
解决方式:
将 Postman 的传参改为 x-www-form-urlencoded 就可以了。
是因为 @RequestParam 接受JSON时,PostMan的body应选择 x-www-form-urlencoded ,否则使用 json 格式,会导致数据为 null
2.调用第二个接口时,提示如下:
关键字:non-static inner classes like this can only by instantiated using default, no-argument constructor
2021-10-19 11:57:28.726 WARN 18112 --- [nio-9011-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.turing.compare.controller.CompareController$UserInfo` (although at least one Creator exists): non-static inner classes like this can only by instantiated using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.turing.compare.controller.CompareController$UserInfo` (although at least one Creator exists): non-static inner classes like this can only by instantiated using default, no-argument constructor at [Source: (PushbackInputStream); line: 2, column: 5]]
json转内部类对象时出错。像这样的非静态内部类只能通过使用默认的无参数构造函数实例化
因此会导致,请求成功了,但是参数信息没有发送过来。
解决方式:
将 非静态内部类转为静态内部类,添加 static 关键字即可。
@Data public static class UserInfo { private String id; private String name; }