引言

在练习使用Axios传post时发现默认使用的是json传参,而servlet提供的getParameter(String s)方法无法解析这种语法,因此了解到Jackson,对其的序列化与反序列化原理很感兴趣,所以浅析一下其原理。

代码测试

// 测试json语句
{"username":"LiHua","password":"233"}

正确User.class

public class User {

    private String username;
    private String password;

    private User() {
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}

正确解析

@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

public class UserErr {

    private String usernameaaa;
    private String password;

    private UserErr() {
    }

    public String getUsernameaaa() {
        return usernameaaa;
    }

    public String getPassword() {
        return password;
    }
}

错误解析

UserErr user = objectMapper.readValue(sb.toString(), UserErr.class);

    System.out.println("username: " + user.getUsernameaaa());
    System.out.println("password: " + user.getPassword());

分别输出:
成功:
成功
失败:
失败

结论猜测:

内部使用了反射,通过寻找与解析出常量同名同类型变量来创建对象,因为使用了反射的缘故,所以无视私有构造方法。

最后修改:2022 年 09 月 14 日
如果觉得我的文章对你有用,请随意赞赏