zoukankan      html  css  js  c++  java
  • SpringMVC 目标方法返回 json 格式数据

    第一种方法:使用  @ResponseBody 注解来实现

      1、Spring MVC 配置 <mvc:annotation-driven></mvc:annotation-driven>。添加该配置的作用如下,而我们用到的是。。。

      2、添加 jackson-annotations-2.1.5.jar、jackson-core-2.1.5.jar、jackson-databind-2.1.5.jar 三个注解。

      3、在 handler 目标方法中返回集合类型数据并添加 @ResponseBody 注解

       @ResponseBody
        @RequestMapping("/testJson")
        public List<TestBean> testJson(){
            List<TestBean> list = new ArrayList<TestBean>();
            for (int i = 0; i < 5; i++) {
                list.add(new TestBean(i, "name"+i));
            }
            return list;
        }


    第二种方法:使用JSON工具类将数据转换成 json 格式字符串后,使用 PrintWriter 写回。

      1、添加相关 jar 文件,可以使用 Maven 进行下载,dependency 如下所示,其会自动下载所依赖的 jar 文件,完整的 jar 文件如下所示。

            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.4</version>
                <classifier>jdk15</classifier>
            </dependency>        

               

       2、在目标方法中使用 PrintWriter 将数据写回。

        

      @RequestMapping("getDeptList")
        public void getDeptList(HttpServletResponse response){
            List<Department> deptList = new ArrayList<Department>();
            for(int i = 0; i < 5; i++){//模拟数据库取数据操作
                deptList.add(new Department(i, "name" + i));
            }
            JSONObject jo = JSONObject.fromObject(deptList);
            jo.put("deptList", deptList);
            jo.put("json key", "手动设置的 json value");
            PrintWriter printWriter = null;
            try {
                //设置响应格式及字符编码
                response.setContentType("application/json;charset=UTF-8");
                printWriter = response.getWriter();
                printWriter.print(jo.toString());//写回数据
            } catch (IOException e) {
                e.printStackTrace();
            } finally {//释放相关资源
                if (null != printWriter) {
                    printWriter.flush();
                    printWriter.close();
                }
            }
            return;
        }

      

  • 相关阅读:
    数据库MySQL安装和校验
    字符集和字符编码
    Eclipse之文件【默认编码格式设置】,防止乱码等问题
    一天搞定CSS(扩展):CSS Hack
    Eclipse导入项目常见问题----facet版本问题04
    php 实现python hashlib.md5.digest
    刚安装python,使用pip install安装第三方库报错,提示“由于目标计算机积极拒绝,无法连接”
    Ubuntu 安装 Elasticsearch
    PHP
    php面试题之四——PHP面向对象(基础部分)
  • 原文地址:https://www.cnblogs.com/yjtx/p/4440924.html
Copyright © 2011-2022 走看看