一 . 通过 jackson 返回JSON数据
1. 引入JAR包
jackson-core-asl-1.9.13.jar
jackson-core-lgpl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
jackson-mapper-lgpl-1.9.13.jar
2. Spring配置文件添加
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> |
3. Controller里面修改返回值类型
@RequestMapping(value = "{username}") public @ResponseBody User find(@PathVariable String username, Model model, HttpServletResponse response) { User u = users.get(username); return u; } |
二 . 通过 PrintWriter 输出字符串返回JSON数据
@RequestMapping(value = "{username}") public void find2_1(@PathVariable String username, HttpServletResponse response) { Gson gson = new Gson(); User u = users.get(username); String us = gson.toJson(u); // 需要设置编码格式,否则可能出现乱码 response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); try { PrintWriter out = response.getWriter(); out.print(us); } catch (IOException e) { e.printStackTrace(); } } |