`
starscream
  • 浏览: 286008 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring MVC 学习笔记 九 json格式的输入和输出

阅读更多
Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用

		<!-- json -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-lgpl</artifactId>
			<version>1.8.1</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-lgpl</artifactId>
			<version>1.8.1</version>
		</dependency>



先修改之前的helloworld.jsp,增加客户端json格式的数据输入。
	var cfg = 	{
	    type: 'POST', 
	    data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}), 
	    dataType: 'json',
	    contentType:'application/json;charset=UTF-8',	    
	    success: function(result) { 
	        alert(result.success); 
	    } 
	};

function doTestJson(actionName){
	cfg.url = actionName;
	$.ajax(cfg);
}



根据前面的分析,在spring mvc中解析输入为json格式的数据有两种方式
1:使用@RequestBody来设置输入
    @RequestMapping("/json1")
    @ResponseBody
	public JsonResult testJson1(@RequestBody User u){
    	log.info("get json input from request body annotation");
    	log.info(u.getUserName());
    	return new JsonResult(true,"return ok");
}


2:使用HttpEntity来实现输入绑定
    @RequestMapping("/json2")    
    public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u){
    	log.info("get json input from HttpEntity annotation");
    	log.info(u.getBody().getUserName());
    	ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>( new JsonResult(true,"return ok"),HttpStatus.OK);
    	return responseResult;
}


Json格式的输出也对应有两种方式
1:使用@responseBody来设置输出内容为context body
2:返回值设置为ResponseEntity<?>类型,以返回context body
另外,第三种方式是使用ContentNegotiatingViewResolver来设置输出为json格式,需要修改servlet context配置文件如下
	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
			</map>
		</property>
		<property name="defaultViews">
			<list>
				<bean
					class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>

但这种格式的输出会返回{model类名:{内容}} 的json格式,
例如,以下代码
    @RequestMapping("/json3.json")
    public JsonResult testJson3(@RequestBody User u){
    	log.info("handle json output from ContentNegotiatingViewResolver");
    	return new JsonResult(true,"return ok");
    }

期望的返回是 {success:true,message:”return ok”};
但实际返回的却是 {"jsonResult":{"success":true,"msg":"return ok"}}
原因是MappingJacksonJsonView中对返回值的处理未考虑modelMap中只有一个值的情况,直接是按照mapName:{mapResult}的格式来返回数据的。
修改方法,重载MappingJacksonJsonView类并重写filterModel方法如下
    protected Object filterModel(Map<String, Object> model) {  
        Map<?, ?> result = (Map<?, ?>) super.filterModel(model);  
        if (result.size() == 1) {  
            return result.values().iterator().next();  
        } else {  
            return result;  
        }  
    }  


对应的ContentNegotiatingViewResolver修改如下
<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
			</map>
		</property>
		<property name="defaultViews">
			<list>
				<bean
					class="net.zhepu.json.MappingJacksonJsonView" />
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>
6
2
分享到:
评论
6 楼 di1984HIT 2015-12-06  
学习了~~
5 楼 estn_h 2013-06-25  
4L 正解哦
4 楼 ajie 2013-05-20  

不需要扩展重载MappingJacksonJsonView类并重写filterModel方法
可通过设置,达到目的:
<property name="extractValueFromSingleKeyModel" value="true"/>
3 楼 yaofengzhu 2013-04-25  
代码运行没有问题
2 楼 zhangbd_Answer 2012-03-07  
    @RequestMapping("/json3.json") 
    public JsonResult testJson3(@RequestBody User u){ 
        log.info("handle json output from ContentNegotiatingViewResolver"); 
        return new JsonResult(true,"return ok"); 
    } 

这里好像少了@ResponseBody吧,初学者,如果不对,请博主纠正。
1 楼 amigobot 2011-08-26  
modelmap被封装进json,然后type信息就没了,里面的内容都都成了linkedhashmap. 想解决这个问题想了一下午了, 也想到了重载MappingJacksonJsonView.filerModel, 还有就是ObjectMapper。 有没有更简单的办法呢?

相关推荐

Global site tag (gtag.js) - Google Analytics