zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    su的使用与退出
    338. Counting Bits
    c语言学习笔记
    Linux命令
    vimrc
    CSS选择器
    链表//设计链表
    数组和字符串//反转字符串中的单词 III
    CSS样式基本知识
    开始学习CSS,为网页添加样式
  • 原文地址:https://www.cnblogs.com/youcoding/p/14888537.html
Copyright © 2011-2022 走看看