spring MVC如何返回json呢?

有两种方式:

方式一:使用ModelAndView

Java代码  
  1. @ResponseBody
  2. @RequestMapping("/save")
  3. public ModelAndView save(SimpleMessage simpleMessage){
  4. //查询时可以使用 isNotNull
  5. if(!ValueWidget.isNullOrEmpty(simpleMessage)){
  6. try {
  7. //把对象中空字符串改为null
  8. ReflectHWUtils.convertEmpty2Null(simpleMessage);
  9. } catch (SecurityException e) {
  10. e.printStackTrace();
  11. } catch (NoSuchFieldException e) {
  12. e.printStackTrace();
  13. } catch (IllegalArgumentException e) {
  14. e.printStackTrace();
  15. } catch (IllegalAccessException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. simpleMessage.setCreateTime(TimeHWUtil.getCurrentTimestamp());
  20. simpleMessage.setHasReply(Constant2.SIMPLE_MESSAGE_HAS_REPLY_NOT_YET);
  21. this.simpleMessageDao.add(simpleMessage);
  22. Map map=new HashMap();
  23. map.put("result", "success");
  24. return new ModelAndView(new MappingJacksonJsonView(),map);
  25. }

方式二:返回String

Java代码  
  1. /***
  2. * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"}
  3. * @param file
  4. * @param request
  5. * @param response
  6. * @return
  7. * @throws IOException
  8. */
  9. @ResponseBody
  10. @RequestMapping(value = "/upload")
  11. public String upload(
  12. @RequestParam(value = "image223", required = false) MultipartFile file,
  13. HttpServletRequest request, HttpServletResponse response)
  14. throws IOException {
  15. String content = null;
  16. Map map = new HashMap();
  17. if (ValueWidget.isNullOrEmpty(file)) {
  18. map.put("error", "not specify file!!!");
  19. } else {
  20. System.out.println("request:" + request);// org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest@7063d827
  21. System.out.println("request:" + request.getClass().getSuperclass());
  22. // // System.out.println("a:"+element+":$$");
  23. // break;
  24. // }
  25. String fileName = file.getOriginalFilename();// 上传的文件名
  26. fileName=fileName.replaceAll("[\\s]",   "");//IE中识别不了有空格的json
  27. // 保存到哪儿
  28. String finalFileName = TimeHWUtil.formatDateByPattern(TimeHWUtil
  29. .getCurrentTimestamp(),"yyyyMMddHHmmss")+ "_"
  30. + new Random().nextInt(1000) + fileName;
  31. File savedFile = getUploadedFilePath(request,
  32. Constant2.UPLOAD_FOLDER_NAME + "/image", finalFileName,
  33. Constant2.SRC_MAIN_WEBAPP);// "D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\ upload\\pic\\ys4-1.jpg"
  34. System.out.println("[upload]savedFile:"
  35. + savedFile.getAbsolutePath());
  36. // 保存
  37. try {
  38. file.transferTo(savedFile);
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. ObjectMapper mapper = new ObjectMapper();
  43. map.put("fileName", finalFileName);
  44. map.put("path", savedFile.getAbsolutePath());
  45. try {
  46. content = mapper.writeValueAsString(map);
  47. System.out.println(content);
  48. } catch (JsonGenerationException e) {
  49. e.printStackTrace();
  50. } catch (JsonMappingException e) {
  51. e.printStackTrace();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. //          System.out.println("map:"+map);
  56. }
  57. /*
  58. * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"}
  59. * */
  60. return content;
  61. }

两种方式有什么区别呢?

方式一:使用ModelAndView的contentType是"application/json"

方式二:返回String的            contentType是"text/html"

那么如何设置response的content type呢?

使用注解@RequestMapping 中的produces:

Java代码  
  1. @ResponseBody
  2. @RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")
  3. public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)
  4. throws IOException {
  5. String content = null;
  6. Map map = new HashMap();
  7. ObjectMapper mapper = new ObjectMapper();
  8. map.put("fileName", "a.txt");
  9. try {
  10. content = mapper.writeValueAsString(map);
  11. System.out.println(content);
  12. } catch (JsonGenerationException e) {
  13. e.printStackTrace();
  14. } catch (JsonMappingException e) {
  15. e.printStackTrace();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. if("json".equals(contentType2)){
  20. response.setContentType(SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF);
  21. }
  22. return content;
  23. }

@RequestMapping(value ="/upload",produces="application/json;charset=UTF-8")

@RequestMapping(value = "/upload",produces="application/json")

spring 官方文档说明:

Producible Media Types

You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {// implementation omitted
}

Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.

Tip

The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.

参考:http://hw1287789687.iteye.com/blog/2128296

http://hw1287789687.iteye.com/blog/2124313

spring MVC 返回json相关推荐

  1. Spring学习手册 1:Spring MVC 返回JSON数据

    目录 完整代码在这 Spring MVC对JSON数据格式的支持非常好,配置完成后什么都不用管靠注解就可以轻松返回JSON格式的数据. Spring 对JSON的支持有三种方式,下面会一一介绍,在此之 ...

  2. spring mvc 返回json数据到ajax报错parseerror问题

    最近使用ajax接收spring mvc传过来的json数据时总是出现parseerror的错误,错误源码如下: 前端: $.ajax({type: 'POST',url: "groupFu ...

  3. Spring mvc 返回json格式 - 龙企阁 - 博客频道 - CSDN.NET

    第一次使用spring mvc ,在此也算是记录一下以防忘记,希望有经验的朋友指出不足的地方 一.使用maven管理jar. [html] view plaincopyprint? <depen ...

  4. Spring MVC 返回json数据 报406错误 问题解决方案

    将jackson jar包改为jackson-databind-2.5.0.jar  jackson-core-2.5.0.jar  jackson-annotations-2.5.0.jar(这个版 ...

  5. Java Web(11) Spring MVC 返回Json

    2019独角兽企业重金招聘Python工程师标准>>> 1. 首先是对Spring mvc 进行xml配置 <?xml version="1.0" enco ...

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

    一.返回ModelAndView,其中包含map集 /** 返回ModelAndView类型的结果* 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{ ...

  7. spring mvc返回json

    1. @ResponseBody的注解 Spring3.0 MVC @ResponseBody的作用是把返回值直接写到HTTP response body里   2. 第二种使用JSON工具将对象序列 ...

  8. java去除json 转移,Spring MVC返回的json去除根节点名称的方法

    这篇文章主要介绍了Spring MVC返回的json去除根节点名称的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下 spring xml中配置视图如果是如下 那么返回结果会是: {" ...

  9. java json 返回null,[] Spring4 MVC 返回json格式时候 设置不返回null值属性的有关问题...

    [求助] Spring4 MVC 返回json格式时候 设置不返回null值属性的问题 本帖最后由 bighong0404 于 2015-10-06 12:45:38 编辑 背景: 使用@respon ...

最新文章

  1. 努力的孩子运气不会太差,跌宕的人生定当更加精彩
  2. 在高并发分布式情况下生成唯一标识id
  3. java 比较算法_JAVA排序算法实现和比较:冒泡,桶,选择,快排,归并
  4. Modbus协议栈综合实例设计
  5. QT5开发及实例学习之十五Qt5位置相关函数
  6. IOS炫酷的引导界面
  7. es过滤指定数据 java_elasticsearch 结构化搜索_在案例中实战基于range filter来进行范围过滤...
  8. 代码级操作指南 | 如何在Docker Swarm中运行服务
  9. python写入文件不覆盖_Python第7课:不一样的新建文件
  10. python3.6爬淘宝信息
  11. gulp怎么运行html文件,如果gulp-watch监视html文件,它会运行所有任务
  12. Leetcode. 14. Longest Common Prefix
  13. 初学者C语言输入输出挖坑填补处须知
  14. 台式计算机找不到无线连接,台式机如何连接wifi_台式机找不到无线网络
  15. 开源项目 CDN 加速服务站合集:除了BootCDN,你还知道其他免费的前端开源项目 CDN 加速服务吗
  16. java笔记——(集合)
  17. linux窗口按钮,在KDE Linux中配置窗口装饰按钮 | MOS86
  18. SVM分类器中损失函数梯度求法及理解
  19. python爱好者社区 投稿_2018年Python爱好者社区历史文章合集(作者篇)
  20. Oracle force-cr-override flush造成数据库卡顿问题排查思路

热门文章

  1. 【全文】Libra回应质疑:Facebook将放弃控制权,不与主权货币竞争
  2. 22页PPT告诉你5G产业最新投资机会!
  3. 5G的3大应用场景落地开花,中国或将引领全球5G产业发展
  4. 美国智库报告:自动驾驶对社会、经济与劳动力的影响
  5. 斯坦福大学科学家研发微型植入式神经刺激器
  6. 密歇根大学联合谷歌大脑提出,通过「推断语义布局」实现「文本到图像合成」
  7. Facebook最新对抗学习研究:无需「平行语料库」完成「无监督」机器翻译
  8. 元宵节来了,程序员用 Python 送你一盏 3D 花灯
  9. 新信号!阿里 AI 工程师趋于年轻化,高端AI人才严重短缺
  10. vim介绍,vim颜色显示,vim一般模式下移动光标,vim一般模式下的复制、剪切和粘贴...