基本作用
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