Loading... ## 引言 在练习使用Axios传post时发现默认使用的是json传参,而servlet提供的getParameter(String s)方法无法解析这种语法,因此了解到Jackson,对其的序列化与反序列化原理很感兴趣,所以浅析一下其原理。 ### 代码测试 ```json // 测试json语句 {"username":"LiHua","password":"233"} ``` 正确User.class ```java public class User { private String username; private String password; private User() { } public String getUsername() { return username; } public String getPassword() { return password; } } ``` 正确解析 ```java @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("POST!!!"); // 读取请求内容 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8)); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } // 解析json ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(sb.toString(), User.class); System.out.println("username: " + userErr.getUsername()); System.out.println("password: " + userErr.getPassword()); } ``` 错误UserErr.class ```java public class UserErr { private String usernameaaa; private String password; private UserErr() { } public String getUsernameaaa() { return usernameaaa; } public String getPassword() { return password; } } ``` 错误解析 ```java UserErr user = objectMapper.readValue(sb.toString(), UserErr.class); System.out.println("username: " + user.getUsernameaaa()); System.out.println("password: " + user.getPassword()); ``` 分别输出: 成功: ![成功](https://cdn2.feczine.cn/2022/09/14/63218596c038b.jpg) 失败: ![失败](https://cdn2.feczine.cn/2022/09/14/6321859734ef9.jpg) ### 结论猜测: 内部使用了反射,通过寻找与解析出常量同名同类型变量来创建对象,因为使用了反射的缘故,所以无视私有构造方法。 最后修改:2022 年 09 月 14 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 本作品采用 CC BY-NC-SA 4.0 International License 进行许可。