基本作用
ObjectMapper 是 Jackson 提供的一个类,作用是将 java 对象与 json 字符串相互转化。
常用的方法writeValueAsString
。
比如在 SpringSecurity 中,登录成功后的回调如下:
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
// 返回 json 格式的数据
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter();
Hr hr = (Hr) authentication.getPrincipal();
hr.setPassword(null);
RespBean ok = RespBean.ok("登录成功", hr);
String string = new ObjectMapper().writeValueAsString(ok);
System.out.println(string);
writer.write(string);
writer.flush();
writer.close();
}
})
其中
String string = new ObjectMapper().writeValueAsString(ok);
就是调用 ObjectMapper
的 writeValueAsString
方法将 RespBean
对象,写入 json 字符串中。
参考资源
https://blog.csdn.net/weixin_39916392/article/details/79400368