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();
        }        
    }
复制代码

 

 
posted @   Franson  阅读(12605)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示