spring mvc 返回json数据的四种方式

一.返回ModelAndView,其中包含map集

/*
     * 返回ModelAndView类型的结果
     * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true})
     */
    @RequestMapping(value = "/checkNameExistsMethod2", produces = "application/json;charset=UTF-8") //这里的produces值在不设置的情况下将根据返回结果自动决定
    public @ResponseBody
    ModelAndView checkNameValidMethod2(@RequestParam String name) {
        boolean result = true;
       //...
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        return new ModelAndView(new MappingJackson2JsonView(), map);
    }
 

二.返回String类型的json,这里有两种方式。

方式一:使用jackson-databind-x.x.x.jar包中的ObjectMapper将Map型数据改写为String并返回

  /*
     * 返回String类型的结果
     * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true})
     */
    @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String checkNameValidMethod1(@RequestParam String name) {
        boolean result = true;
        //...
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }
 

方式二:

直接返回字符串,主要key/value值必须使用含有转义字符的双引号,单引号无效 

 /*
     * 返回String类型的结果
     * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true})
     */
    @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String checkNameValidMethod1(@RequestParam String name) {
        boolean result = true;
     
        String resultString = "{"result":true}"; //注意一定是双引号 "{"result":"success"}"
      
        return resultString;
    }

三.返回任何预定义class类型的结果:

@RequestMapping(value = "/findEmployeebyName")
    public @ResponseBody
    Employee findEmployeebyName(String name) {
        List<Employee> lstEmployees = employeeService.getAllEmployees();
        for (Employee employee : lstEmployees) {
            if (employee.getName().equals(name))
                return employee;
        }
        return null;
    }

这里的Employ必须事先定义好。

四.使用HttpServletResponse对象的response.getWriter().write(xxx)方法

@RequestMapping(value="/forbiddenUser")
    public void forbiddenUser(int id,HttpServletRequest request,HttpServletResponse response) {
        String resultString="{"result":"success"}";//注意一定是双引号 "{"result":true}"    
        try {
            response.setContentType("application/json");
            response.getWriter().write(resultString);
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
 
原文地址:https://www.cnblogs.com/franson-2016/p/5613610.html