yjtx

第一种方法:使用  @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;
    }

 

 

  

 

分类:

技术点:

相关文章: