ObjectMapper 的用法


基本作用

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);

就是调用 ObjectMapperwriteValueAsString 方法将 RespBean 对象,写入 json 字符串中。

参考资源

https://blog.csdn.net/weixin_39916392/article/details/79400368


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM