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