springMVC如何返回json呢?
有两种方式:
方式一:使用ModelAndView
Java代码 @ResponseBody@RequestMapping("/save")publicModelAndViewsave(SimpleMessagesimpleMessage){//查询时可以使用isNotNullif(!ValueWidget.isNullOrEmpty(simpleMessage)){try{//把对象中空字符串改为nullReflectHWUtils.convertEmpty2Null(simpleMessage);}catch(SecurityExceptione){e.printStackTrace();}catch(NoSuchFieldExceptione){e.printStackTrace();}catch(IllegalArgumentExceptione){e.printStackTrace();}catch(IllegalAccessExceptione){e.printStackTrace();}}simpleMessage.setCreateTime(TimeHWUtil.getCurrentTimestamp());simpleMessage.setHasReply(Constant2.SIMPLE_MESSAGE_HAS_REPLY_NOT_YET);this.simpleMessageDao.add(simpleMessage);Mapmap=newHashMap();map.put("result","success");returnnewModelAndView(newMappingJacksonJsonView(),map);}
方式二:返回String
Java代码 /****{"fileName":"1002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\1002125209_571slide4.jpg"}*@paramfile*@paramrequest*@paramresponse*@return*@throwsIOException*/@ResponseBody@RequestMapping(value="/upload")publicStringupload(@RequestParam(value="image223",required=false)MultipartFilefile,HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{Stringcontent=null;Mapmap=newHashMap();if(ValueWidget.isNullOrEmpty(file)){map.put("error","notspecifyfile!!!");}else{System.out.println("request:"+request);//org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest@7063d827System.out.println("request:"+request.getClass().getSuperclass());////System.out.println("a:"+element+":$$");//break;//}StringfileName=file.getOriginalFilename();//上传的文件名fileName=fileName.replaceAll("[\\s]","");//IE中识别不了有空格的json//保存到哪儿StringfinalFileName=TimeHWUtil.formatDateByPattern(TimeHWUtil.getCurrentTimestamp(),"yyyyMMddHHmmss")+"_"+newRandom().nextInt(1000)+fileName;FilesavedFile=getUploadedFilePath(request,Constant2.UPLOAD_FOLDER_NAME+"/image",finalFileName,Constant2.SRC_MAIN_WEBAPP);//"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\pic\\ys4-1.jpg"System.out.println("[upload]savedFile:"+savedFile.getAbsolutePath());//保存try{file.transferTo(savedFile);}catch(Exceptione){e.printStackTrace();}ObjectMappermapper=newObjectMapper();map.put("fileName",finalFileName);map.put("path",savedFile.getAbsolutePath());try{content=mapper.writeValueAsString(map);System.out.println(content);}catch(JsonGenerationExceptione){e.printStackTrace();}catch(JsonMappingExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}//System.out.println("map:"+map);}/**{"fileName":"1002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\1002125209_571slide4.jpg"}**/returncontent;}
两种方式有什么区别呢?
方式一:使用ModelAndView的contentType是"application/json"
方式二:返回String的contentType是"text/html"
那么如何设置response的content type呢?
使用注解@RequestMapping 中的produces:
Java代码 @ResponseBody@RequestMapping(value="/upload",produces="application/json;charset=UTF-8")publicStringupload(HttpServletRequestrequest,HttpServletResponseresponse,StringcontentType2)throwsIOException{Stringcontent=null;Mapmap=newHashMap();ObjectMappermapper=newObjectMapper();map.put("fileName","a.txt");try{content=mapper.writeValueAsString(map);System.out.println(content);}catch(JsonGenerationExceptione){e.printStackTrace();}catch(JsonMappingExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}if("json".equals(contentType2)){response.setContentType(SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF);}returncontent;}
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 theAcceptrequest header matches one of these values. Furthermore, use of theproducescondition ensures the actual content type used to generate the response respects the media types specified in theproducescondition. For example:
@Controller@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET,produces="application/json")@ResponseBodypublic Pet getPet(@PathVariableString petId, Model model) {// implementation omitted}
Just like withconsumes, producible media type expressions can be negated as in!text/plainto match to all requests other than those with anAcceptheader value oftext/plain.
Tip
参考:/blog/2128296
/blog/2124313
如果觉得《spring MVC 返回json》对你有帮助,请点赞、收藏,并留下你的观点哦!