ModelAndView返回json类型数据

一.自定义bean,手动在返回数据时将数据json化 
1.自定义类JacksonUtil.java,类中实现tojson方法(即将数据转成json类型); 
2.自定义类JsonView 继承 AbstractView 
3.xml中配置bean:jsonView 
4.配置bean class为spring的BeanNameViewResolver,是根据viewName选择相应名称的bean 
使用方法:ModelAndView mv=new ModelAndView(“jsonView”)

二.使用注解@ResponseBody 
需要添加支持的jar包 jackson.jar包。 
例:public @ResponseBody String test(String arg0) 
@ResponseBody详细解说参见:http://blog.csdn.net/qh_java/article/details/51654783


Spring MVC 同一个方法同时返回view或json
@RequestMapping(value = "/htmlorjson/{type}", method = {RequestMethod.GET, RequestMethod.POST})  
    public ModelAndView ajaxPaymentBatchApproveProcess(@PathVariable String type)  
    {  
        if ("html".equals(type))  
        {  
             //index表示指定路径下的jsp页面的名称  
            ModelAndView mav = new ModelAndView("index");  
            return mav;  
        }  
        else  
        {  
            ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());  
            mav.addObject("result", "failed");  
            return mav;  
        }  
    }  

原文地址:https://www.cnblogs.com/thewindkee/p/12873183.html