求大神指点!ModelAndView如何转成Json

buaazhuo 2015-07-26 11:59:42
请问在没有jsp的情况下,如何把ModelAndView如何转成Json,在一个web工程,简单的实验一下方法如下,在tomcat上执行,却返回错误,得不到json。如果返回的是String或pojo类就可以得到json串。已经加入了json的jar包。跪求大神指点啊@!!!(比如在配置全局异常处理的方法时,需要实现HandlerExceptionResolver接口,而此接口必须返回ModelAndView,就是这种情况)
@ResponseBody
@RequestMapping(value="/testjson3")
public ModelAndView getUserses3(){
ActivityCustom activityCustom = new ActivityCustom();
ModelAndView modelAndView = new ModelAndView();
activityCustom.setId(30);
activityCustom.setName("huodong");
activityCustom.setParticipateNum(30);
modelAndView.addObject(activityCustom);
return modelAndView;
}
...全文
1829 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
为啥必须返回ModelAndView啊,返回String不行啊
Defonds 2015-07-27
  • 打赏
  • 举报
回复
是的 ResponseBody 的话就是返回 json 或者对象了。 如何让 Spring MVC Controller 的同一个 URL 请求,根据逻辑判断返回 JSON 或者 HTML 视图? 自定义 JsonView 类, 见http://blog.csdn.net/defonds/article/details/7419640
bartholomew4 2015-07-27
  • 打赏
  • 举报
回复
由于不常用SPRING MVC,我常做的是直接返回字符串,简单粗暴。 另外的几种方法: 1. @ResponseBod,推荐用这种吧SPRING MVC常用这种
@ResponseBody
	public JSONObject test(HttpServletResponse response,
			@ModelAttribute("id") Long id) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", "猫");
		jsonObject.put("Max.score", new Integer(100));
		jsonObject.put("Min.score", new Integer(50));
		jsonObject.put("nickname", "picglet");
		return jsonObject;
	} 
spring MVC的适配器配置,我这里配置的是默认的UTF-8,你可以根据自己的需求变更编码
<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
				<bean
					class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
				<bean
					class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/plain;charset=UTF-8</value>
						</list>
					</property>
				</bean>
				<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!-- 					class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> -->
					<property name="supportedMediaTypes">
						<list>
							<value>application/json;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>
2.spring 2的遗留产品,现在貌似不用了 <bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 或者<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> 需要jackson包 3.序列化然后反序列化,NO ZUO NO DIE。。。。

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧